Reputation: 27
I'm working on a broken CSV file which uses 3 blanks as a separation. Is there any possible way to delimit it as tabs with python3? Currently my code looks like this:
import csv
with open ("example.csv", "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter ="\ ")
with open("new_example.csv","w") as new_file:
csv_writer = csv.writer(new_file, delimiter="\t")
for line in csv_reader:
csv_writer.writerow(line)
With this I'm getting the error that it's only possible to delimit it with 1-character. Another problem is, that the cells in the csv-file often contain 1 blank (shouldn't be separated).
Upvotes: 1
Views: 2412
Reputation: 12620
As the error says csv
can only separate on one character and it is probably of no use here. Just use .replace
to turn sequences of three spaces into tabs.
with (open("example", "r") as csv_file,
open("new_example.csv", "w") as new_file):
for line in csv_file:
new_file.write(line.replace(' ', '\t'))
Upvotes: 0
Reputation: 27879
Well if pandas
is viable for you, this should sort you out:
import pandas as pd
inFile = pd.read_csv('example.csv', sep='\s+')
inFile.to_csv('new_example.csv', sep='\t')
Upvotes: 3