I want to convert the .txt file to a .csv file.

Asked 2 years ago, Updated 2 years ago, 85 views

The following .csv file was output under python 3.6 environment:I want to convert this to a comma (,) delimited .csv file, but it doesn't work.The element in the first row of zepp.csv contains abcdef and has a blank separation.I would like to write a code that applies an algorithm that corrects these to a,b,c,d,e,f separated by commas to each component.Below is a list of the codes you have tried.

import csv
with open(zepp.csv, 'w') as f:
    writer=csv.writer(f, delimiter=',')

I also used pandas, but it didn't work as I wanted.

python python3 pandas csv

2022-09-30 19:54

2 Answers

writer I just generated an object, but there is no process to write to the file.

Although exception handling is omitted (although we do not take into account the absence of the = file or the non-half-width space separation), I think the following code is acceptable.

import csv
importos

os.rename('zepp.csv', 'backup_zepp.csv')
with open('backup_zepp.csv') as fin, open('zepp.csv', 'w') as fout:
    o=csv.writer(fout)
    For line in fin:
        o.writerow(line.split())


2022-09-30 19:54

Assuming that the original TXT file does not have a header row and CSV file does not require both header row and index column, pandas is

import pandas as pd
df=pd.read_table('zepp.txt', header=None,delim_whitespace=True)
df.to_csv('zepp.csv', index=False, header=False)

I think it would be good to


2022-09-30 19:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.