python 读文件有段代码看不明白:input_fileopen(data.txt,r)for line in input_file:lineline.strip
python 读文件
有段代码看不明白:
input_file=open("data.txt","r")
for line in input_file:
line=line.strip()
print line
input_file.close()
这个文件直接打开,不用读?再循环里面这个line又是什么呢?
[解决办法]http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.
>>>
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will be returned.
>>>
>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:
>>>
>>> for line in f:
print line,
This is the first line of the file.
Second line of the file
The alternative approach is simpler but does not provide as fine-grained control. Since the two approaches manage line buffering differently, they should not be mixed.