简体   繁体   中英

Different level of spacing between rows on different lines while converting a csv file to txt file using python

I have to convert a.csv file into.txt file which I did and I have the following code.

text_list = []

csv_file = 'test.csv'
with open(csv_file,"r") as infile:
    for line in infile:
        line = line.split(",", 2)
        text_list.append("\t".join(line))

txt_file = 'test.txt'
with open(txt_file, 'w') as outfile:
    for line in text_list:
        outfile.write(" " + line)
    outfile.close

But the problem is,

CSV file:

phi,Z,T
0,0,0
10.000005,1.2,3000.00
20.000005,2.4,6000.00

Required txt file:

phi        Z    T
0          0    0
10.000005  1.2  3000.00
20.000005  2.4  6000.00

Text file I have with the above mentioned code:

phi    Z    T
0    0    0
10.000005    1.2    3000.00
20.000005    2.4    6000.00

Thank you

You can use the string method ljust to add spaces to your string so that it has a certain length. Therefore, you read the input file line by line, split each line on commas and append that to text_list , which results in a list of lists with each word of each row.

Then we compute the number of columns num_cols from the length of the first row. Then we calculate the length of the longest word / number in each column with a nested list comprehension. We use this to ljust every word according to the max length of the respective column.

text_list = []

csv_file = 'test.csv'
with open(csv_file,"r") as infile:
    for line in infile:
        line = line.rstrip().split(",", 2)
        text_list.append(line)

num_cols = len(text_list[0])
max_lengths = [max([len(line[i]) for line in text_list]) for i in range(num_cols)]

txt_file = 'test.txt'
with open(txt_file, 'w') as outfile:
    for line in text_list:
        outfile.write('\t'.join([word.ljust(max_lengths[i]) for i, word in enumerate(line)]) + '\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM