How to Read Text File With Delimiter in Python
Python has always remained the first choice for most of the Information technology folks who honey automation. With Python, you merely demand a few lines of lawmaking to automate various IT tasks, one of those is working with files. Python can read files, create them, and a whole lot more than.
In this tutorial, you will learn how to write Python code to open, read and write to text files with tons of examples.
Let's get started!
Prerequisites
This tutorial volition exist a footstep-past-step tutorial. If you'd like to follow along, ensure you have the post-obit in identify:
- Python v3.6 or subsequently – This tutorial volition be using Python v3.9.two on a Windows 10 machine.
- A code editor – This tutorial volition use Visual Studio (VS) Code.
Opening a Text File with Python
Permit's get this tutorial started by get-go learning how to open a file for reading in Python.
1. Open your favorite lawmaking editor; preferably one like VS Code.
2. Create a simple text file inside the home directory (~) and proper noun it as devops.txt with the text *"*Hello, ATA friends."
iii. Now, create a file and copy the Python code shown beneath to it and then relieve information technology every bit a Python script called ata_python_read_file_demo.py in your dwelling house directory.
# newfile is the file object , devops.txt is the file to be opened and default Admission manner is read newfile = open('devops.txt') # Declaring the Access manner "read" exclusively # newfile = open('devops.txt' , 'r') impress(newfile) The in a higher place script contains the Python congenital-in method open up() that opens the devops.txt file for reading without declaring an access way. The open() method then returns a file stream which gets captured in the newfile variable.
Once you have a file object, that object contains methods and attributes to perform diverse operations. When opening files, depending on what y'all intend to practice with the file, you must define a specific mode as explained higher up in the inline comments. There are various modes to open files in Python.
-
r– Open the file for reading. This is the default access mode. -
westward– Open the file for writing. -
x– This choice creates a new file if information technology no file exists but fails if already nowadays. -
a– Opens the file for writing and appends the information at the end of file. -
b– Opens the file in binary fashion. This mode is used to work with files other than text such as pdf, images, etc. -
t– Open the file in text mode. This is the default mode. -
+– Opens the file to read or write.
4. Now, execute the Python script.
python ata_python_read_file_demo.py The output will display the file stream with details such every bit blazon of file, access way, and encoding.
Once you have the file open, you can then read, write or modify it many different means.
Reading a Text File with Python
Once you take a file open in Python, it's time to do something to it. Permit's first cover how to read a text file. If you need to read the content inside the file, you'll demand to employ a Python role called read().
With the ata_python_read_file_demo.py Python script open in your code editor from higher up, replace the text with the following Python code, save and execute it.
The script below reads the entire file as a file stream, reads each line of the file ane at a fourth dimension and reads the kickoff five characters of each line.
# Reading the file as 1 file stream file = open up('devops.txt', 'r') # Reads the entire file at once and places the contents in retention. read_content = a.read() print(read_content) # Iterating over each line in the text file with the with keyword # and reading each line one at a time with open up('devops.txt', 'r') as line: # Reads a specific line of text in the file. line_text = c.readline() impress(line_text) # Iterating over each line in the text file with the with keyword # and reading the first five characters of each line with open up('devops.txt', 'r') as line: # Reads a specific number of characters from a single line of text in the file. read_char = line.read(5) impress(read_char)
Reading a CSV File with Python
You've learned that Python can open up simple text files. CSV files are, in actuality, just text files with a specific schema. You could use the open up() method using the read() or readline() method to read CSV rows but it wouldn't be too useful. Why? Because the read methods don't understand a CSV file'south schema.
To read a CSV file and then that Python understands the data the CSV stores, utilise the CSV Python module.
Bold you are still in your code editor:
1. Open up another tab and paste in the following CSV data and save information technology as ata_csv_demo.csv. You'll come across that this CSV data contains 4 columns and four rows.
Date, PreviousUserCount, UserCountTotal, sitepage 02-01-2021,61,5336, ATA.com/web log 03-01-2021,42,5378, ATA.com/blog1 04-01-2021,26,5404, ATA.com/blog2 05-01-2021,65,5469, ATA.com/blog3 ii. Now, open another tab, create the following Python script save it as a Python script with a proper noun of your choosing. This Python script below:
- Imports the
csvmodule to brand the methods available. - Opens the ata_csv_demo.csv file for reading.
- Reads each row in the CSV file with the
reader()method telling Python that the row is delimited with a comma. - Uses a
forloop to read the text in each row returning a Python list for each CSV record.
# Import the CSV module import csv # Open the CSV file for reading and brainstorm iterating over each row with open('ata_csv_demo.csv' , 'r') as csv_row: ## Parse the line as comma-delimited csv_data = csv.reader(csv_row, delimiter=',') # Output specific rows from csv files using the for-loop and iterates over the range() office for _ in range(5): print(adjacent(csv_data)) print(read) In the output below, y'all'll meet where the script has iterated through the CSV file to testify only the outset 5 rows.
Appending to a Text File with Python
When you open a text file in Python, you aren't only relegated to reading. You lot can likewise write to text files. Permit's cover in this section how to suspend text to an existing file.
You can write to a text file via one of two methods:
-
write()– Writes the contents as a string to the file. -
writelines()– Writes multiple strings simultaneously to the file.
Now, allow's learn to append data into a text file. To do so, open another tab in your code editor, re-create and paste the post-obit Python code, save it as a Python script name of your choosing, and execute it.
The beneath script is opening the devops.txt file you created before and appending a single line to information technology with the write() method. It'due south then using the writeLines() method to suspend multiple lines at one time.
# Open the file for appending (a) and begin reading each line with open('devops.txt', 'a') as file: file.write("\nAdding 5 more than ATA friend") file.writelines(['\nAdding 5 more than ATA friend', '\nAdding fifteen more than ATA friend'])
Writing Data in a CSV File with Python
By now, you take learned how to open a CSV file using Python. There are numerous times when you lot'll demand to add information into CSV files, such as adding your customer'southward information, employees' salary records, employee ID, etc. Python makes your life easier writing to CSV files.
To append rows into the aforementioned file devops.csv which y'all created before, open a new code editor tab and paste the following Python script into your lawmaking editor, save and execute it.
# importing the csv module import csv # open up office within with statement Here y'all used newline since the csv module does its ain (universal) newline handling. with open('devops.csv','a', newline='') every bit csv_file: # open up() function along with append way "a"and newline='' write_csv = csv.author(csv_file, delimiter=',') # csv.writer() is used to write content in the CSV file write_csv.writerow(['08-08-2021','68','8888', 'ATA.com/blog8']) # csv.writerow() to add a row and append the contentExecute the writing_into_csv.py script using Python, Open devops.csv and check out the terminal row!
Decision
Today y'all've learned how to open, write and read different file types using Python. Using Python drastically reduces the chances of man errors compared to when you perform these mundane tasks manually.
Now that you can quickly and easily process data at speeds that you've never thought possible before, why non automate more of your data handling tasks with Python?
Source: https://adamtheautomator.com/python-read-file/
0 Response to "How to Read Text File With Delimiter in Python"
Post a Comment