python基礎(5)-文件操做

文件(file)操做

建立文件html

verse.txt:python

牀前明月光
疑是地上霜

open(path(文件路徑),mode(模式:r/r+[讀],w/w+[寫],a/a+[追加])):返回文件句柄(對象)

 1 verse_file = open('verse.txt','r',encoding="utf-8") app

r/r+[讀],w/w+[寫],a/a+[追加]的區別

mode 可作操做 若文件不存在 是否覆蓋
r 只讀 報錯 -
r+ 讀寫 報錯
w 只寫 建立
w+ 讀寫 建立
a 只寫 建立 追加
a+ 讀寫 建立 追加

readlines():獲取全部行,返回list

1 verse_file = open('verse.txt','r',encoding="utf-8")
2 print(verse_file.readlines())
3 verse_file.close()
4 #result:
5     #['牀前明月光\n', '疑是地上霜']

read():讀取全部字符,返回string

1 verse_file = open('verse.txt','r',encoding="utf-8")
2 print(verse_file.read())
3 verse_file.close()
4 #result:
5     # 牀前明月光
6     # 疑是地上霜

遍歷文件最優法(懶加載)

verse_file = open('verse.txt','r',encoding="utf-8")
for row in verse_file:
    print(row.strip())
#result:
    # 牀前明月光
    # 疑是地上霜

write():寫入.當mode爲'w'[寫]時,會清空以前的內容再寫入;當mode爲'a'[追加]時,會在原來基礎上繼續追加寫入

1 verse_file = open('verse.txt','w',encoding="utf-8")
2 input_str = '舉頭望明月\n低頭思故鄉'
3 verse_file.write(input_str)
4 verse_file.close()
5 """
6 verse.txt:
7     舉頭望明月
8     低頭思故鄉
9 """
 1 verse_file = open('verse.txt','a',encoding="utf-8")
 2 input_str = '舉頭望明月\n低頭思故鄉'
 3 verse_file.write(input_str)
 4 verse_file.close()
 5 """
 6 verse.txt:
 7     牀前明月光
 8     疑是地上霜舉頭望明月
 9     低頭思故鄉
10 """

seek(position):定位光標位置

verse_file = open('verse.txt','r',encoding="utf-8")
verse_file.seek(6)#utf-8中一箇中文字符佔3個字節
print(verse_file.read())
verse_file.close()
"""
 verse.txt:
    明月光
    疑是地上霜
"""

tell():獲取光標位置

1 verse_file = open('verse.txt','r',encoding="utf-8")
2 verse_file.seek(6)
3 print(verse_file.tell());#result:6

練習

多級目錄文件持久化增刪改查

address.dic:編碼

{}

file.py:spa

 1 file = open('address.dic', 'r', encoding='utf8')
 2 history_list = []
 3 address_dic = eval(file.read())
 4 while True:
 5     print('---當前地址---')
 6     for current in address_dic:
 7         print(current)
 8     choose = input('請選擇---0:返回上一層,1:新增,2:刪除,3:修改,4:查詢,5:保存退出:')
 9     if choose == '0':
10         if history_list:
11             address_dic = history_list.pop();
12     elif choose == '1':
13         insert_name = input('請輸入新增項名稱:')
14         if insert_name in address_dic:
15             print('新增失敗!該名稱項已存在!')
16             continue;
17         else:
18             address_dic[insert_name] = {}
19     elif choose == '2':
20         delete_name = input('請輸入刪除項名稱:')
21         if delete_name not in address_dic:
22             print('刪除失敗!該名稱項不存在!')
23             continue;
24         else:
25             del address_dic[delete_name];
26     elif choose == '3':
27         modify_name = input('請輸入修改項名稱:')
28         if modify_name not in address_dic:
29             print('修改失敗!該名稱項不存在!')
30             continue;
31         else:
32             modify_to_name = input('請輸入修改後的名稱:')
33             modify_value = address_dic[modify_name];
34             address_dic[modify_to_name] = modify_value
35             del address_dic[modify_name]
36     elif choose == '4':
37         select_name = input("請輸入查詢項名稱:")
38         if select_name not in address_dic:
39             print('查詢失敗!該名稱項不存在!')
40             continue;
41         else:
42             history_list.append(address_dic)
43             address_dic = address_dic[select_name]
44             if not address_dic:
45                 print('當前無地址')
46     elif choose == '5':
47         file = open('address.dic', 'w+', encoding='utf8')
48         if history_list:
49             file.write(str(history_list[0]))
50         else:
51             file.write(str(address_dic))
52         file.close();
53         break;
54     else:
55         print("輸入錯誤")

運行結果:3d

address.dic:code

1 {'湖北': {'武漢': {}}, '廣東': {'深圳': {}}}

擴展

eval(str):可將對應格式字符串轉成相應類型對象.例:

1 dic_str = "{'1':'a','2':'b'}"
2 list_str = "['1','2','3']"
3 dic = eval(dic_str)
4 list = eval(list_str)
5 print(dic,type(dic))
6 print(list,type(list))
7 #result:
8     # {'1': 'a', '2': 'b'} <class 'dict'>
9     # ['1', '2', '3'] <class 'list'>

with:相似C#中Using塊,當前塊執行完釋放對象.下面兩塊代碼等價.

1 with open("test",'r') as file:
2     file.read();
1 file = open("test",'r')
2 file.read()
3 file.close()

編碼與解碼

推薦博客:http://www.javashuo.com/article/p-etclaczz-ca.htmlhtm

相關文章
相關標籤/搜索