Opening a text file in Python
Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open()
function.
Syntax:
File_object = open("File_Name", "Access_Mode")
Parameters:
- File_Name: The name of the file that is needed to be opened.
- Access_Mode: Access modes govern the type of operations possible in the opened file.
Following are the most commonly used access modes:
- Read Only (‘r’): Open text file for reading.
- Write Only (‘w’): Open the file for writing.
- Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data.
- Read and Write (‘r+’): Open the file for reading and writing.
Note: By default, Python assumes the access mode as read i.e (“r”)
# Python program to demonstrate # opening a file # Open function to open the file "myfile.txt" # (same directory) in read mode and store # it's reference in the variable file1 file1 = open ( "myfile.txt" ) # Reading from file print (file1.read()) file1.close() |
Note: For more information, refer to Open a File in Python.
Saving a Text File in Python
After learning about opening a File in Python, let’s see the ways to save it. Opening a new file in write mode will create a file and after closing the file, the files get saved automatically. However, we can also write some text to the file. Python provides two methods for the same.
- write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
- writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Example:
# Python program to demonstrate # saving a text file file = open ( 'read.txt' , 'w' ) file .write( 'Welcome to Geeks for Geeks' ) file .close() |
Output:
With Statement
with
statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close()
when using with
statement. The with
statement itself ensures proper acquisition and release of resources.
Syntax:
with open filename as file: statement(s)
Example:
# Python program to demonstrate # saving a text file with open ( 'read.txt' , 'w' ) as file : books = [ 'Welcome\n' , 'Geeks\n' , 'to\n' , 'Geeks\n' , 'for\n' , 'Geeks\n' , 'world\n' ] file .writelines( "% s\n" % data for data in books) |
Output:
Note: For more information, refer to Writing to file in Python.
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats.