How To Handle Plain Text Files in Python 3
Published on Aug. 22, 2023, 12:16 p.m.
To handle plain text files in Python 3, you can use the built-in file handling functions to create, open, read and write text files. Here are the basic steps:
Step 1: Creating a Text File
You can use the open()
function to create a new text file. This function takes two arguments - the name of the file and the mode in which to open it. Here is an example:
file = open("example.txt", "w")
This will create a new text file named “example.txt” in write mode.
Step 2: Opening a File
Once you have created the file, you can open it for reading or writing using the open()
function. Here is an example:
file = open("example.txt", "r")
This will open the text file named “example.txt” in read mode.
Step 3: Reading a File
To read the contents of a text file, you can use the read()
or readline()
function. The read()
function will read the entire contents of the file, while the readline()
function will read one line at a time. Here is an example:
file = open("example.txt", "r")
contents = file.read()
print(contents)
This will print the entire contents of the “example.txt” file.
Step 4: Writing a File
To write to a text file, you can use the write()
function. Here is an example:
file = open("example.txt", "w")
file.write("Hello World!")
file.close()
This will write the string “Hello World!” to the “example.txt” file.
Finally, it’s important to remember to close the file when you’re done with it to free up system resources. You can do this using the close()
function, as shown in the above examples.
These are just some basic examples of how to handle plain text files in Python 3. There are many more functions and methods available for more advanced file handling operations.