1.文件讀取的三種方法
方法一:
f = open("foo.txt") # 返回一個文件對象
line = f.readline() # 調用文件的 readline()方法
while line:
print line, # 後面跟 ',' 將忽略換行符
# print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
方法二:
for line in open("foo.txt"):
print line,
方法三:
f = open("c:\\1.txt","r")
lines = f.readlines()#讀取全部內容
for line in lines
print line
wirte()方法把字符串寫入文件,writelines()方法可以把列表中存儲的內容寫入文件。
f=file("hello.txt","w+")
li=["hello world\n","hello china\n"]
f.writelines(li)
f.close()
文件的內容:
hello world
hello china
write()和writelines()這兩個方法在寫入前會清除文件中原有的內容,再重新寫入新的內容,相當於“覆蓋”的方法。如果需要保留文件中原有的內容,只是需要追加新的內容,可以使用“a+”模式
打開文件。
f=file("hello.txt","a+")
new_context="goodbye"
f.write(new_content)
f.close()
此時hello.txt中的內容如下所示:
hello world
hello china
goodbye
實踐:
>>> f=file("hello.txt","w+")
>>> li=["hello world\n","hello china\n"]
>>> f.writelines(li)
>>> f.close()
>>>
>>> f=file("hello.txt","a+")
>>> new_context="goodbye"
>>> f.write(new_content)
>>> f.write(new_content)
>>> f.close()
結果:
hello world
hello china
goodbyegoodbye