1、打開文件的方式
f = open("data.txt","r") #設置文件對象
f.close() #關閉文件
#爲了方便,避免忘記close掉這個文件對象,可以用下面這種方式替代
with open('data.txt',"r") as f: #設置文件對象
str = f.read() #可以是隨便對文件的操作
2、文件的讀取方式
- 將文本中的內容讀取到data裏面
f = open("2.txt","r") #設置文件對象
data = f.read() #將txt文件的所有內容讀入到字符串str中
f.close() #將文件關閉
- 按行讀取文件內容
第一種方式
data = []
for line in open("2.txt","r"): #設置文件對象並讀取每一行文件
data.append(line) #將每一行文件加入到list中
print(line)
第二種方式
# f = open('2.txt','r')
# data = f.readlines()
# print(data)
# f.close()
3、文件的寫入方式
- 第一種
with open('2.txt','w') as f: #設置文件對象
str = "hello,da"
f.write(str) #將字符串寫入文件中
‘a’:追加
with open('2.txt', 'a') as f:
f.write('\nHello, world!,dddddd')
- 第二種
data =["abc","def"]
f = open('2.txt','w')
f.writelines(data)
f.close()
- 將 print() 函數的輸出重定向到一個文件中去。
在 print() 函數中指定 file 關鍵字參數,像下面這樣:
with open('1.txt', 'a+') as f:
print('Hello World!', file=f)