Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[-]
Welcome
You have to register before you can post on our site.

Username:


Password:





[-]
Discord Widget

[-]
Twitter: SickGaming

[-]
Latest Threads
[Tut] Python Find Shortest List in List
Last Post: xSicKxBot
Today 02:42 AM
» Replies: 0
» Views: 0
News - Sly Cooper Celebrates 20 Years Wi...
Last Post: xSicKxBot
Today 02:41 AM
» Replies: 0
» Views: 0
PC - Isonzo
Last Post: xSicKxBot
Today 02:41 AM
» Replies: 0
» Views: 0
[Tut] How to Delete a Line from a File i...
Last Post: xSicKxBot
Yesterday 09:31 AM
» Replies: 0
» Views: 0
[Tut] PHP Excel Export Code (Data to Fil...
Last Post: xSicKxBot
Yesterday 09:31 AM
» Replies: 0
» Views: 0
News - Pierce Brosnan Doesn't Care Who T...
Last Post: xSicKxBot
Yesterday 09:30 AM
» Replies: 0
» Views: 0
PC - Broken Pieces
Last Post: xSicKxBot
Yesterday 09:30 AM
» Replies: 0
» Views: 0
[Tut] Python Find Longest List in List
Last Post: xSicKxBot
09-23-2022 01:19 PM
» Replies: 0
» Views: 0
[Tut] How to Capture Screenshot of Page ...
Last Post: xSicKxBot
09-23-2022 01:19 PM
» Replies: 0
» Views: 0
(Indie Deal) Fantasy Idols Bundle, HITMA...
Last Post: xSicKxBot
09-23-2022 01:19 PM
» Replies: 0
» Views: 0

[Tut] How to Convert Multiple Text Files to a Single CSV in Python?

#1
How to Convert Multiple Text Files to a Single CSV in Python?

5/5 – (1 vote)

You can merge multiple text files to a single CSV file in Python by using the glob.glob('./*.txt') expression to filter out all path names of text files in a given folder. Then iterate over all those path names and use the open() function to read the file contents and write append them to the CSV.

Example: merge those files

Here’s the simple example:

import glob with open('my_file.csv', 'a') as csv_file: for path in glob.glob('./*.txt'): with open(path) as txt_file: txt = txt_file.read() + '\n' csv_file.write(txt) 

The resulting output CSV file shows that all text files have been merged:


You can replace the separator (e.g., from single empty space to comma) by using the txt.replace(' ', ',') function before writing it in the CSV:

import glob with open('my_file.csv', 'a') as csv_file: for path in glob.glob('./*.txt'): with open(path) as txt_file: txt = txt_file.read() + '\n' txt = txt.replace(' ', ',') csv_file.write(txt) 

The resulting CSV is neatly separated with comma characters:


In case you need some more advanced ways to convert the text files to the CSV, you may want to check out the Pandas read_csv() function to read the CSV into a DataFrame.

As soon as you have it as a DataFrame, you can do advanced processing such as merging, column selection, slicing, etc.

🌍 Related Tutorial: How to Read a CSV to a DataFrame?



https://www.sickgaming.net/blog/2022/08/...in-python/
Reply





Users browsing this thread:
1 Guest(s)

πš‚Μ·πš’Μ·πšŒΜ·πš”Μ·π™ΆΜ·πšŠΜ·πš–Μ·πš’Μ·πš—Μ·πšΜ· π™·Μ·πš˜Μ·πš–Μ·πšŽΜ·

Copyright Β© SickGaming.net 2022