Reading and Writing Files
To open a file:
Let us look at the example first:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# # Read and write files using the built-in Python file methods # def main(): # Open a file for writing and create if it doesn't exist f = open("mytxtfile.txt", "w+") # Open the file for appending text to the end # write some lines of data to the file for i in range(5, 10): f.write("This is line number " + str(i) + "\r\n") # close the file when done f.close() if __name__ == "__main__": main() |
- f = open(“mytxtfile.txt”, “w+”) ; Argument filename to operate on
- Kind of access to give W write permission and +
sign to create the file if it does not already exist
Read the file content:
1 2 3 4 5 6 7 8 |
def main(): f = open("mytxtfile.txt", "r") if f.mode == 'r': contents = f.read() print(contents) if __name__ == "__main__": main() |
contents = f.read() is used to read a file content.
Read the file line by line.
If your file is large it is not a good idea to read the whole file at once so we can read the file line by line. We use readlines for this Let us look at the example
1 2 3 4 5 6 7 8 9 |
def main(): f = open("mytxtfile.txt", "r") if f.mode == 'r': c = f.readlines() for a in c: print(a) if __name__ == "__main__": main() |