Read and Write text to files in Python
Reading and Writing text to files in Python
There are two types of files Text Files and Binary Files. Text files contain human-readable content however Binary contains machine-understandable binary language content. In this tutorial you are going to learn how to read and write to text files in Python.
File Access Modes
Following are the files access modes in Python used for reading, writing, and appending like operations:
"r"= This file access mode is used to read the file.
"w" = This file access mode used to write content to file. It will overwrite existing content.
"a" = By using this mode you can append content to end of the file.
Write Text to Files
To open the file and append the content you should pass “a” access mode as the parameter of the
open() function. While to overwrite existing contents of the file you should pass “w” access mode as a parameter of the
Append the contents to the end of the file:
#You can also use following way to specify file path # f2 = open(r"C:\Files\testfile2.txt", "a") # open the file f2 = open("testfile2.txt", "a") f2.write("This content will be added to end of file") f2.close() # Now open and read the file after writing content f = open("testfile2.txt", "r") print(f.read())
Open the existing file and overwrite the contents:
# open the file f3 = open("testfile3.txt", "w") f3.write("This content will be overwritten to the file") f3.close() # Now open and read the file after writing content f = open("testfile3.txt", "r") print(f.read())
Creating a New File
To create a new file following file access modes used in Python with
“x” = It creates a new file if it exists then will give an error.
“w” = It creates a new file If the file doesn’t exist.
Create a new file with “x” access mode it doesn’t exist:
f1 = open("testfile1.text","x")
Create a new file with “w” access mode:
f4 = open("testfile4.text","w")
You have successfully learned how to Read and Write text to files in Python. If you have any queries don’t forget to comment below.
C strcpy() function
Python length of list
C++ abs() Absolute Value with Examples
Python square root sqrt() method
How to Export Pandas DataFrame to the CSV File
C++ strncmp() function with example
numpy.dtype() in Python
numpy.where() in Python with Examples
Insertion Sort in Java
length and length() in Java
PHP implode() function
Python raw_input() function with Example