Following
methods are used to read file contents.
a.
read
b.
readline
c.
readlines
read(size)
Reads 'size'
bytes of data and returns it as a string or bytes object. If size is negative
(or) omitted, all the file contents are returned. If the end of the file has
been reached, f.read() will return an empty string ('').
>>> f=open("/Users/harikrishna_gurram/data.txt") >>> f.read() 'First line\nSecond line\nThird line\nFourth line\n'
readline
Read single
line from file. A newline character (\n) is left at the end of the string.
Return an empty string, if the file reaches to end.
>>> f=open("/Users/harikrishna_gurram/data.txt") >>> f.readline() 'First line\n' >>> f.readline() 'Second line\n' >>> f.readline() 'Third line\n' >>> f.readline() 'Fourth line\n' >>> f.readline() ''
readlines
'readlines'
method is used to read all the lines of a file as list.
>>> data=f.readlines() >>> data ['First line\n', 'Second line\n', 'Third line\n', 'Fourth line\n']
Reading a file using for loop
For reading lines from a file, you can loop over
the file object.
>>> f=open("/Users/harikrishna_gurram/data.txt") >>> for line in f: ... print(line) ... First line Second line Third line Fourth line
As you observe output, new line is printed after every line. You can get rid of this by passing ‘end’ parameter to print method.
>>> f=open("/Users/harikrishna_gurram/data.txt") >>> for line in f: ... print(line, end='') ... First line Second line Third line Fourth line
No comments:
Post a Comment