06-25-2022, 10:31 AM
Python Convert CSV to Text File (.csv to .txt)
5/5 – (1 vote)
Basic Challenge
Here’s the content of an example CSV file used in our code snippet below:
If you visualize this CSV in table form, it looks like this:
Name |
Job |
Age |
Income
Alice |
Programmer |
23 |
110000
Bob |
Executive |
34 |
90000
Carl |
Sales |
45 |
50000
The basic problem is to convert the CSV file to a new TXT file as is without changing its content
We start with exploring this basic challenge and build from there by changing the delimiter and using Pandas to access individual columns.
But first things first: How to convert a CSV file to a TXT file without changing its contents?
Method 1: CSV to TXT Unchanged
If you want to keep the content (including the delimiter) in the CSV file unmodified, the conversion is simple: read the file and write its content into a new file using the , , and functions without importing any library.
In other words, perform the three steps to write a CSV to a TXT file unmodified:
Here’s the code snippet that solves our basic challenge:
Little-Known Fact: Python allows multiple expressions in the context manager ( opening line) if you separate them with a comma.
The content of the and files is identical:
So far, so good. But what if you have a slightly different problem:
Method 2: CSV to TXT Empty Space Delimiter
Challenge: How to convert a CSV file to a TXT file in Python by replacing the delimiter with the empty space ?
Example: Convert the following file…
… to this file …
Here’s the simple solution to this challenge:
If you want to change the delimiter to an empty string in the new TXT file, read the file and write its content into a new file using the , , , and functions without importing any library.
To convert a CSV to a TXT file in Python, perform the following steps:
So far, so good. But in Python, there are always many ways to solve a problem. Let’s have a look at a powerful alternative to the no-library approach used before:
Method 3: CSV to TXT using Pandas
Assuming you’ve already installed pandas in your local environment, you can write a CSV to a TXT file in Python pandas using the following four steps:
Here’s the basic Python example:
Little-Known Fact: Python’s function allows you to write a string directly into a fileobject if you use the argument as shown in the code snippet.
The output of the previous code snippet is as follows:
Beautiful, isn’t it?![[Image: 1f49c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f49c.png)
Let’s have a look at the last variation of the “CSV to TXT” problem addressed in this tutorial:
Method 4: CSV Columns or Rows to TXT using Pandas
How to write one or more individual columns or rows of the CSV file into a TXT file using Python Pandas?
The content in a new file:
Of course, you can also select individual rows or multiple columns like so:
The content of the new file shows that only the first two rows have been taken due to the slicing operation in the previous code snippet:
Done! You’ve earned some programming enjoyment:
Programmer Humor
❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.
Conclusion
I hope you enjoyed reading this article and learned something new. Feel free to join our email newsletter with free cheat sheets and weekly Python tutorials:
5/5 – (1 vote)
Basic Challenge
Here’s the content of an example CSV file
Code:
"my_file.csv"Code:
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000If you visualize this CSV in table form, it looks like this:
Name |
Job |
Age |
Income
Alice |
Programmer |
23 |
110000
Bob |
Executive |
34 |
90000
Carl |
Sales |
45 |
50000
The basic problem is to convert the CSV file
Code:
"my_file.csv"Code:
"my_file.txt"Code:
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000We start with exploring this basic challenge and build from there by changing the delimiter and using Pandas to access individual columns.
But first things first: How to convert a CSV file to a TXT file without changing its contents?
Method 1: CSV to TXT Unchanged
If you want to keep the content (including the delimiter
Code:
','Code:
.csvCode:
.txtCode:
open()Code:
read()Code:
write()In other words, perform the three steps to write a CSV to a TXT file unmodified:
- Open the CSV file in reading mode and the TXT file in writing mode.
- Read the CSV file and store it in a variable.
- Write the content into the TXT file.
Here’s the code snippet that solves our basic challenge:
Code:
# 1. Open the CSV file in reading mode and the TXT file in writing mode
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: # 2. Read the CSV file and store in variable content = f_in.read() # 3. Write the content into the TXT file f_out.write(content)
Little-Known Fact: Python allows multiple expressions in the context manager (Code:
withThe content of the
Code:
.csvCode:
.txtCode:
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000So far, so good. But what if you have a slightly different problem:
Method 2: CSV to TXT Empty Space Delimiter
Challenge: How to convert a CSV file to a TXT file in Python by replacing the delimiter
Code:
','Code:
' 'Example: Convert the following file
Code:
'my_file.csv'Code:
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000… to this file
Code:
'my_file.txt'Code:
Name Job Age Income
Alice Programmer 23 110000
Bob Executive 34 90000
Carl Sales 45 50000Here’s the simple solution to this challenge:
If you want to change the delimiter
Code:
','Code:
' 'Code:
.csvCode:
.txtCode:
open()Code:
read()Code:
string.replace()Code:
write()To convert a CSV to a TXT file in Python, perform the following steps:
- Open the CSV file in reading mode and the TXT file in writing mode.
- Read the CSV file into a string.
- Create a new string by replacing all occurrences of the delimiter with the empty stringCode:
','.Code:' '
- Write the content into the TXT file.
Code:
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: content = f_in.read().replace(',', ' ') f_out.write(content)So far, so good. But in Python, there are always many ways to solve a problem. Let’s have a look at a powerful alternative to the no-library approach used before:
Method 3: CSV to TXT using Pandas
Assuming you’ve already installed pandas in your local environment, you can write a CSV to a TXT file in Python pandas using the following four steps:
- Import the library.Code:
pandas
- Read the CSV file into a DataFrame using .Code:
pd.read_csv()
- Convert the DataFrame to a String using the built-in function.Code:
str()
- Print the string to a file using the file argument of the function, for example.Code:
print()
Here’s the basic Python example:
Code:
import pandas as pd df = pd.read_csv('my_file.csv')
content = str(df)
print(content, file=open('my_file.txt', 'w'))
Little-Known Fact: Python’s Code:
print()Code:
fileThe output of the previous code snippet is as follows:
Code:
Name Job Age Income
0 Alice Programmer 23 110000
1 Bob Executive 34 90000
2 Carl Sales 45 50000Beautiful, isn’t it?
![[Image: 1f49c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f49c.png)
Let’s have a look at the last variation of the “CSV to TXT” problem addressed in this tutorial:
Method 4: CSV Columns or Rows to TXT using Pandas
How to write one or more individual columns or rows of the CSV file into a TXT file using Python Pandas?
- Import the library.Code:
pandas
- Read the CSV file into a DataFrame using .Code:
pd.read_csv()
- Select the column(s) or row(s) to write into the TXT file from the DataFrame using Pandas indexing or slicing.
- Call to convert the DataFrame to a string in a human-readable way.Code:
df.to_string()
- Print the string to a file using the file argument of the function, for example.Code:
print()
Code:
import pandas as pd df = pd.read_csv('my_file.csv')
content = str(df['Name'])
print(content, file=open('my_file.txt', 'w'))The content in a new file
Code:
'my_file.txt'Code:
0 Alice
1 Bob
2 CarlOf course, you can also select individual rows or multiple columns like so:
Code:
import pandas as pd df = pd.read_csv('my_file.csv')
content = df['Name'][:2].to_string()
print(content, file=open('my_file.txt', 'w'))The content of the new file
Code:
'my_file.txt'Code:
[:2]Code:
0 Alice
1 BobDone! You’ve earned some programming enjoyment:
Programmer Humor
Code:
Question: How did the programmer die in the shower? ☠❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.
Conclusion
I hope you enjoyed reading this article and learned something new. Feel free to join our email newsletter with free cheat sheets and weekly Python tutorials:

