In this lesson, we will be learning how to work with text files in Python.
There are built-in functions for working with files in python. The open() function returns a file object and is most commonly used with two arguments: open(filename, mode)
f = open('workfile', 'w')
Similarly, the close() function closes the file object and removes any unwritten information. It is simply used in the following form:
f.close()
The read() function reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). Size is an optional numeric argument. The write() function writes the contents of a passed in string to the file.
Here is an example program that demonstrates a read/write operation in Python.
# Example of file operations for a sample text file # Creating a new text file with writing permission with open("sample.txt", 'w', encoding = 'utf-8') as f: # Writing to the file f.write("First line\n") f.write("Second line\n") f.write("Third line\n") # Closing the file f.close()
OUTPUT: First line Second line Third line
We can also read in the contents of the fine using the following lines of code:
# Opening the sample.txt file with reading permissions with open("sample.txt", 'r') as f: print(f.read()) # Closing the file f.close()
OUTPUT: First line Second line Third line
End of Course
With this, we have come to the end of our Python Programming for Newbies course. We hope that this course is a stepping stone for your journey in programming with Python. If you have any questions or feedback, feel free to let us know in the comment section.
Also, now that you are able to code in Python, you can enroll in a domain-specific course by going through all of our specialization courses.
(As a reminder, we are constantly updating our courses. So, make sure that you check in, in the future as well!