How to Use Python to Create Read Update and Write to a File Projects
Python File Handling
In Python, at that place is no need for importing external library to read and write files. Python provides an inbuilt part for creating, writing, and reading files.
In this file treatment in Python tutorial, nosotros will learn:
- How to Open a Text File in Python
- How to Create a Text File in Python
- How to Append Text File in Python
- How to Read Files in Python
- How to Read a File line by line in Python
- File Modes in Python
How to Open a Text File in Python
To open a file, y'all need to utilize the congenital-in open
function. The Python file open function returns a file object that contains methods and attributes to perform various operations for opening files in Python.
Syntax of Python open up file function
file_object = open up("filename", "mode")
Here,
- filename: gives proper name of the file that the file object has opened.
- fashion: attribute of a file object tells you which mode a file was opened in.
More details of these modes are explained beneath
How to Create a Text File in Python
With Write to file Python, you tin create a .text files (guru99.txt) past using the code, we have demonstrated here:
Footstep ane) Open the .txt file
f= open up("guru99.txt","w+")
- We declared the variable "f" to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a cord that represents the kinds of permission or functioning we desire to do on the file
- Hither, we used "w" letter in our argument, which indicates Python write to file and it will create file in Python if information technology does not be in library
- Plus sign indicates both read and write for Python create file operation.
Step two) Enter data into the file
for i in range(x): f.write("This is line %d\r\n" % (i+ane))
- Nosotros take a for loop that runs over a range of x numbers.
- Using the write function to enter data into the file.
- The output we want to iterate in the file is "this is line number", which we declare with Python write file function and then percent d (displays integer)
- Then basically nosotros are putting in the line number that we are writing, then putting information technology in a carriage return and a new line grapheme
Step iii) Close the file instance
f.close()
- This will close the instance of the file guru99.txt stored
Hither is the result afterwards lawmaking execution for create text file in Python example:
When you click on your text file in our case "guru99.txt" it will await something like this
How to Suspend Text File in Python
Yous can also suspend/add together a new text to the already existing file or a new file.
Footstep ane)
f=open("guru99.txt", "a+")
One time again if you lot could see a plus sign in the code, information technology indicates that it volition create a new file if it does not be. Simply in our case nosotros already take the file, then we are not required to create a new file for Python suspend to file operation.
Step 2)
for i in range(2): f.write("Appended line %d\r\n" % (i+i))
This will write data into the file in suspend mode.
You can see the output in "guru99.txt" file. The output of the code is that before file is appended with new data past Python append to file operation.
How to Read Files in Python
You can read a file in Python by calling .txt file in a "read mode"(r).
Footstep 1) Open the file in Read mode
f=open("guru99.txt", "r")
Step 2) Nosotros use the mode function in the code to bank check that the file is in open mode. If yes, we proceed alee
if f.manner == 'r':
Step 3) Use f.read to read file data and store it in variable content for reading files in Python
contents =f.read()
Step 4) Impress contents for Python read text file
Hither is the output of the read file Python example:
How to Read a File line past line in Python
You tin likewise read your .txt file line by line if your data is too big to read. readlines() lawmaking will segregate your data in easy to read mode.
When you run the code (f1=f.readlines()) to read file line by line in Python, it will divide each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read manner. But if there is a circuitous data file which is not readable, this slice of code could exist useful.
File Modes in Python
Following are the various File Modes in Python:
Mode | Clarification |
---|---|
'r' | This is the default mode. It Opens file for reading. |
'w' | This Mode Opens file for writing. If file does non exist, it creates a new file. If file exists it truncates the file. |
'x' | Creates a new file. If file already exists, the operation fails. |
'a' | Open file in append mode. If file does not exist, it creates a new file. |
't' | This is the default fashion. It opens in text mode. |
'b' | This opens in binary manner. |
'+' | This will open a file for reading and writing (updating) |
Here is the complete lawmaking for Python print() to File Case
Python 2 Case
def main(): f= open("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\n" % (i+1)) f.shut() #Open the file dorsum and read the contents #f=open("guru99.txt", "r") # if f.mode == 'r': # contents =f.read() # print contents #or, readlines reads the individual line into a listing #fl =f.readlines() #for x in fl: #print x if __name__== "__main__": main()
Python three Case
Below is another Python impress() to File Instance:
def main(): f= open up("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\due north" % (i+1)) f.shut() #Open up the file back and read the contents #f=open("guru99.txt", "r") #if f.style == 'r': # contents =f.read() # print (contents) #or, readlines reads the private line into a list #fl =f.readlines() #for x in fl: #print(x) if __name__== "__main__": main()
Summary
- Python allows you to read, write and delete files
- Use the part open("filename","w+") for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions.
- To suspend data to an existing file or Python print to file operation, use the command open up("Filename", "a")
- Use the Python read from file function to read the Unabridged contents of a file
- Use the readlines function to read the content of the file ane by one.
Source: https://www.guru99.com/reading-and-writing-files-in-python.html
0 Response to "How to Use Python to Create Read Update and Write to a File Projects"
Post a Comment