Files Input and Output
You can open and use files for reading or writing by creating an object of the file class and using its read, readline or write methods appropriately to read from or write to the file. The ability to read or write to the file depends on the mode you have specified for the file opening. Then finally, when you are finished with the file, you call the close method to tell Python that we are done using the file.
#!/usr/bin/python # Filename: using_file.py poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = open('poem.txt', 'w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default while True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print(line, end='') f.close() # close the file
$ python using_file.py Programming is fun When the work is done if you wanna make your work also fun: use Python!
How It Works:
First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode ('r'), write mode ('w') or append mode ('a'). We can also specify whether we are reading, writing, or appending in text mode ('t') or binary mode ('b'). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a 't'ext file and opens it in 'r'ead mode.
In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.
Next, we open the same file again for reading. We don't need to specify a mode because 'read text file' is the default mode. We read in each line of the file using the readline method in a loop. This method returns a complete line including the newline character at the end of the line. When an empty string is returned, it means that we have reached the end of the file and we 'break' out of the loop.
By default, the print() function prints the text as well as an automatic newline to the screen. We are suppressing the newline by specifying end='' because the line that is read from the file already ends with a newline character. Then, we finally close the file.
Now, check the contents of the poem.txt file to confirm that the program has indeed written to and read from that file.