注:所有代碼部分均為連續(xù)的,“結(jié)果”為在jupyter分步運(yùn)行結(jié)果
代碼部分:
text = 'Writing a text\nhello world'
print(text)
my_file = open('file1.txt','w') #以寫入的方式打開文件,如果文件不存在會(huì)創(chuàng)建該文件,沒有路徑則為當(dāng)前文件夾下
#文件可以加路徑如 E:\python\.....
my_file.write(text)
my_file.close()
結(jié)果:
執(zhí)行后可以進(jìn)入當(dāng)前文件夾下,會(huì)發(fā)現(xiàn)有了'file1.txt'文件,里面有text變量的數(shù)據(jù)
with open('file2.txt','w') as f2:#清空文件,然后寫入 用f2代替文件
f2.write('123123\nhahaha') #這種方式不需要使用.close操作
結(jié)果:
執(zhí)行后可以進(jìn)入當(dāng)前文件夾下,會(huì)發(fā)現(xiàn)有了file2.txt'文件,里面有數(shù)據(jù)
with open('file2.txt','a') as f2: #在文件最后追加內(nèi)容
f2.write(text)
結(jié)果:同上
with open('file2.txt','r') as f2: #以讀取的方式打開文件
content = f2.read() #讀取全部?jī)?nèi)容
print(content)
結(jié)果:
123123
hahahaWriting a text
hello world
with open('file2.txt','r') as f2:
content = f2.readline() #讀取一行內(nèi)容 readline
print(content)
結(jié)果:
123123
with open('file2.txt','r') as f2:
content = f2.readlines() #讀取所有行存放到一個(gè)列表中 readlines
print(content)
結(jié)果:
['123123\n', 'hahahaWriting a text\n', 'hello world']
filename = 'file2.txt'
with open(filename) as f:
for line in f:
print(line.rstrip())#在循環(huán)中print會(huì)自動(dòng)換行,所以要用rstrip()取消本中的換行符
結(jié)果:
123123
hahahaWriting a text
hello world