A file can be either text or binary. A text file is a sequence of lines and a line is a sequence of characters. The line is terminated by a EOL (End Of Line) character. A binary file is any file. Binary files can only be processed if we know the file structure.
Open ( )
open() returns a file object file_object = open(filename, mode) mode is way the file will be used.
'r' when the file will only be read 'w' for only writing (an existing file with the same name will be erased) 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing.
>>> f = open('workfile', 'w') >>> print f
Create a text file
file = open("newfile.txt", "w") file.write("hello python") file.write("and another line") file.close()
How to read a text file
file = open('newfile.txt', 'r') print file.read()
Output: hello world in the new file and another line
We can also specify how many characters the string should return, by using file.read(n), where "n" determines number of characters.
file = open('newfile.txt', 'r') print file.read(5)
The readline() function will read from a file line by line (rather than pulling the entire file in at once).
file = open('newfile.txt', 'r') print file.readline():
readlines() returns the complete file as list of strings
file = open('newfile.txt', 'r') print file.readlines()
Output: ['hello python', 'and another line']
Looping over a file object
file = open('newfile.txt', 'r') for line in file: print line,
Output: hello python and another line
The write method takes one parameter, which is the string to be written. To start a new line after writing the data, add a character to the end.
file = open("newfile.txt", "w") file.write("This is python") file.write("And here is another line") file.close()
Close ( )
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file.