0

I want to convert a .txt file into CSV format. Here's an example of what I have in my .txt file:

0 1
1 346
5 10

Here's the code that I'm using:

import csv
txtfile = r"file.txt"
csvfile = r"file.csv"
with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
    stripped = (line.strip() for line in infile)
    lines = (line.split() for line in stripped if line)
    writer = csv.writer(outfile)
    writer.writerows(lines)

As a result, I get an empty line after every single line with numbers (=> all the even lines are empty): https://i.stack.imgur.com/19QAV.png. There are no empty lines in the .txt file, however.

Could someone please help me figure out why am I getting those extra empty lines in CSV file?

Marooo
  • 21
  • 2
  • What's the reason for the txt-to-csv conversion? If you just want to open the files via a Spreadsheed software, you might consider renaming the file extension and set the import option accordingly. – albert Apr 14 '21 at 09:08
  • Hi @buran! Yes, that's exactly my problem, thanks so much! I wasn't finding this thread before. – Marooo Apr 14 '21 at 10:10
  • Hi @albert! Thank for the comment. In the txt file, I have a list of edges of a directed graph: first column are heads, 2nd column are tail. Using it, I am to compute strongly connected components of this graph, so I thought that CSV format is more convenient than txt for solving this task. I would need "heads" and "tails" to be situated in different columns, while renaming the file extension would place the whole raw into one single cell of the first column; so, unfortunately, simply renaming isn't really helpful here. – Marooo Apr 14 '21 at 10:10
  • The underlying problem seems to be related to your data import options. Renaming the extension from csv to txt does not change the file contents. In addition, both txt and csv are technically the same (plain text files with data). – albert Apr 14 '21 at 10:26

2 Answers2

1

I would suggest an approach with pandas, where you can read the text file into a DataFrame and then write it out to a CSV file:

import pandas as pd

df = pd.read_table('file.txt', sep='\s', engine='python', header=None)
df.to_csv('file.csv', header=False, index=False)

It is probably an overshoot here but it is definitely worth learning pandas

0

csv.writer(outfile) should be csv.writer(outfile, newline=''). This tells the csv-writer to use an empty string as newline. Which means it doesn't use a new line.

PonyTale
  • 306
  • 1
  • 7
  • Thank you! I've also used a link mentioned above by buran, so I've placed the newline here: `with ... open(csvfile, 'w', newline = '') as outfile:` – Marooo Apr 14 '21 at 10:14