Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Convert CSV to Text File (.csv to .txt)

#1
Python Convert CSV to Text File (.csv to .txt)

5/5 – (1 vote)

Basic Challenge


Here’s the content of an example CSV file "my_file.csv" used in our code snippet below:

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

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 "my_file.csv" to a new TXT file "my_file.txt" as is without changing its content

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

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 .csv file and write its content into a new .txt file using the open(), read(), and write() functions without importing any library.

In other words, perform the three steps to write a CSV to a TXT file unmodified:

  1. Open the CSV file in reading mode and the TXT file in writing mode.
  2. Read the CSV file and store it in a variable.
  3. Write the content into the TXT file.

Here’s the code snippet that solves our basic challenge:

# 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 (with opening line) if you separate them with a comma.

The content of the .csv and .txt files is identical:

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

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 'my_file.csv'

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

… to this file 'my_file.txt'

Name Job Age Income
Alice Programmer 23 110000
Bob Executive 34 90000
Carl Sales 45 50000

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 .csv file and write its content into a new .txt file using the open(), read(), string.replace(), and write() functions without importing any library.

To convert a CSV to a TXT file in Python, perform the following steps:

  1. Open the CSV file in reading mode and the TXT file in writing mode.
  2. Read the CSV file into a string.
  3. Create a new string by replacing all occurrences of the delimiter ',' with the empty string ' '.
  4. Write the content into the TXT file.
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:

  1. Import the pandas library.
  2. Read the CSV file into a DataFrame using pd.read_csv().
  3. Convert the DataFrame to a String using the built-in str() function.
  4. Print the string to a file using the file argument of the print() function, for example.

Here’s the basic Python example:

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 print() function allows you to write a string directly into a file object if you use the file argument as shown in the code snippet.

The output of the previous code snippet is as follows:

 Name Job Age Income
0 Alice Programmer 23 110000
1 Bob Executive 34 90000
2 Carl Sales 45 50000

Beautiful, isn’t it? ?

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?

  1. Import the pandas library.
  2. Read the CSV file into a DataFrame using pd.read_csv().
  3. Select the column(s) or row(s) to write into the TXT file from the DataFrame using Pandas indexing or slicing.
  4. Call df.to_string() to convert the DataFrame to a string in a human-readable way.
  5. Print the string to a file using the file argument of the print() function, for example.
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 'my_file.txt':

0 Alice
1 Bob
2 Carl

Of course, you can also select individual rows or multiple columns like so:

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 'my_file.txt' shows that only the first two rows have been taken due to the slicing operation [:2] in the previous code snippet:

0 Alice
1 Bob

Done! You’ve earned some programming enjoyment:

Programmer Humor


❓ 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:



https://www.sickgaming.net/blog/2022/06/...sv-to-txt/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Convert MIDI to MP3 in Python – A Quick Overview xSicKxBot 0 2,395 09-02-2023, 02:04 PM
Last Post: xSicKxBot
  [Tut] 5 Easy Ways to Edit a Text File From Command Line (Windows) xSicKxBot 0 1,324 03-05-2023, 08:32 AM
Last Post: xSicKxBot
  [Tut] Python Video to Text – Speech Recognition xSicKxBot 0 1,148 01-23-2023, 02:55 PM
Last Post: xSicKxBot
  [Tut] Python | Split Text into Sentences xSicKxBot 0 1,176 12-14-2022, 01:24 PM
Last Post: xSicKxBot
  [Tut] How to Convert an Octal Escape Sequence in Python – And Vice Versa? xSicKxBot 0 1,339 12-08-2022, 01:23 PM
Last Post: xSicKxBot
  [Tut] How to Convert Octal String to Integer in Python xSicKxBot 0 1,303 12-04-2022, 08:39 AM
Last Post: xSicKxBot
  [Tut] Python Convert Hex to Base64 xSicKxBot 0 1,283 11-30-2022, 09:32 PM
Last Post: xSicKxBot
  [Tut] How to Create and Run a Batch File That Runs a Python Script? xSicKxBot 0 1,243 11-09-2022, 09:53 PM
Last Post: xSicKxBot
  [Tut] Python Create JSON File xSicKxBot 0 1,258 11-03-2022, 01:09 PM
Last Post: xSicKxBot
  [Tut] How to Filter Data from an Excel File in Python with Pandas xSicKxBot 0 1,229 10-31-2022, 05:36 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016