您的位置:首页 > 编程语言 > Python开发

【Python】文件操作,read(), readline(), readlines()

2014-05-22 16:57 651 查看
To open a file:

open(filename, mode)

mode:

‘r’ to open for reading

'w' to open for writing

'a' to open for appending(adding to what is already in the file)

>>> file = 'C:\\Users\document.txt'   双斜杠避免被解释为转义字符

>>> filename = open(file, 'r')

>>> line = filename.readline()

>>> while line != '':
print(line)
line = filename.readline()

>>> filename.close()

when you want to process every line in a file use the for line in file approach:

for line in file:

process line

file.read(): print the whole document as a string

list = file.readlines():自动将文件分析成一个行的列表,这个列表可由python的for...in...进行处理 如,for line in file.readlines()

readline():read and return the next line from the file, including the newline character(if it exists)

return the empty string if there are no more lines in the file,每次只读取一行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: