Python Read Gz File and Save to Text File
In this tutorial, we'll work on the dissimilar file operations in Python. We'll go over how to utilise Python to read a file, write to a file, delete files, and much more. And so without any filibuster, let's become started.
Working with Files in Python
In the previous tutorial, we used console to take input. Now, we will exist taking input using a file. That means, nosotros will read from and write into files. To do and then, we need to maintain some steps. Those are
- Open up a file
- Accept input from that file / Write output to that file
- Close the file
We will also learn some useful operations such as copy file and delete file.
Why are file operations in Python needed?
When working with large datasets in machine learning issues, working with files is a basic necessity. Since Python is a majorly used language for information science, yous demand to be proficient with the different file operations that Python offers.
So, let's explore some of the Python file operations here.
1. Open a file in Python with the open up() function
The first stride to working with files in Python is to learn how to open a file. You can open files using the open()
method.
The open up() function in Python accepts two arguments. The first ane is the file name forth with the complete path and the second one is the file open style.
Below, I've listed some of the mutual reading modes for files:
- 'r' : This manner indicate that file volition be open for reading merely
- 'w' : This mode bespeak that file will be open for writing only. If file containing containing that name does not exists, information technology volition create a new i
- 'a' : This mode indicate that the output of that program volition be append to the previous output of that file
- 'r+' : This mode indicate that file will be open for both reading and writing
Additionally, for the Windows operating organization, yous can append 'b' for accessing the file in binary. This is is because Windows differentiates between a binary text file and a regular text file.
Suppose, we identify a text file name 'file.txt' in the same directory where our code is placed. Now we want to open that file.
Withal, the open up(filename, way) office returns a file object. With that file object you can go on your further operation.
#directory: /dwelling house/imtiaz/lawmaking.py text_file = open('file.txt','r') #Another method using full location text_file2 = open('/dwelling/imtiaz/file.txt','r') print('First Method') print(text_file) impress('2nd Method') print(text_file2)
The output of the following lawmaking will be
================== RESTART: /home/imtiaz/code.py ================== First Method Second Method >>>
two. Read and write to files in Python
Python offers various methods to read and write to files where each functions behaves differently. 1 of import matter to note is the file operations style. To read a file, you need to open the file in the read or write way. While to write to a file in Python, you need the file to be open up in write mode.
Here are some of the functions in Python that allow you to read and write to files:
- read() : This function reads the unabridged file and returns a string
- readline() : This function reads lines from that file and returns as a cord. It fetch the line northward, if it is been called nth time.
- readlines() : This function returns a list where each element is single line of that file.
- readlines() : This role returns a list where each chemical element is single line of that file.
- write() : This role writes a fixed sequence of characters to a file.
- writelines() : This function writes a list of string.
- append() : This function append string to the file instead of overwriting the file.
Let's take an example file "abc.txt", and read individual lines from the file with a for loop:
#open the file text_file = open('/Users/pankaj/abc.txt','r') #go the list of line line_list = text_file.readlines(); #for each line from the list, print the line for line in line_list: print(line) text_file.close() #don't forget to close the file
Output:
Now, that we know how to read a file in Python, permit'due south move ahead and perform a write functioning here with the writelines() office.
#open the file text_file = open('/Users/pankaj/file.txt','w') #initialize an empty list word_list= [] #iterate 4 times for i in range (i, 5): print("Delight enter information: ") line = input() #have input word_list.suspend(line) #append to the list text_file.writelines(word_list) #write 4 words to the file text_file.shut() #don't forget to close the file
Output
3. Copy files in Python using the shutil() method
We can apply the shutil module to copy files in Python. This utility allows u.s.a. to perform copy and move operations in Python on different files. Let's piece of work on this with an example:
import shutil shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt') #some other way to re-create file shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt') impress("File Copy Done")
four. Delete files in Python with the shutil.bone.remove() method
Python'south shutil module offers the remove() method to delete files from the file system. Let's take a look at how nosotros can perform a delete operation in Python.
import shutil import os #two ways to delete file shutil.os.remove('/Users/pankaj/abc_copy2.txt') os.remove('/Users/pankaj/abc_copy2.txt')
5. Close an open file in Python with the close() method
When you open a file in Python, it's extremely of import to close the file later on you make the changes. This saves whatsoever changes that you've previously made, removes the file from the memory, and prevents whatever further reads or writes within the program.
Syntax to shut an open up file in Python:
If we continue on from our previous examples where nosotros read files, hither's how you'd close the file:
text_file = open('/Users/pankaj/abc.txt','r') # some file operations hither text_file.close()
Additionally, you can avoid closing files manually if you lot use the with block. Equally shortly as the with cake is executed, the files are closed and are no longer available for reading and writing.
six. Python FileNotFoundError
It's common to receive the FileNotFoundError when working with files in Python. It tin be easily avoided past providing complete file paths when creating the file object.
File "/Users/pankaj/Desktop/string1.py", line 2, in <module> text_file = open up('/Users/pankaj/Desktop/abc.txt','r') FileNotFoundError: [Errno two] No such file or directory: '/Users/pankaj/Desktop/abc.txt'
To gear up the FileNotFoundError, yous simply need to verify that the path y'all've mentioned for the file open method is correct.
Conclusion
These are the file operations on Python. At that place are many more than ways you can use files within Python which includes reading CSV data and more. Here's an commodity on how you lot can apply the Pandas module to read CSV datasets in Python.
I hope you enjoyed reading the article! Happy learning 🙂
References:
https://docs.python.org/iii/tutorial/inputoutput.html#reading-and-writing-files
Source: https://www.journaldev.com/14408/python-read-file-open-write-delete-copy
0 Response to "Python Read Gz File and Save to Text File"
Post a Comment