简体   繁体   中英

How to convert a list of list to a string in python?

I have a list which I am reading from a text file 'arrowhead.txt' and it is string. I want to read the string and write it again to another text document in python. I know I could have just copied the text from input file to destination file, but I need to use python for that. Any help? Input file :

arrowhead
BEGIN
28,85
110,80
118,80
127,80
135,80
141,80
147,80
152,80
156,80
160,80
162,80
164,80
165,80
165,80
END
BEGIN
139,38
183,81
186,85
188,86
189,88
190,90
191,92
183,93
180,95
177,96
174,97
170,100
166,102
162,105
157,107
151,110
145,113
140,116
135,118
130,121
126,125
122,125
119,127
117,130
115,130
113,130
112,132
112,132
END

Output file should be in the same format. Need help!

with open('arrowhead.txt', 'r') as f: 
    arwhead = f.readline() 
    splited_line = ([line.rstrip().split(',') for line in f]) 
    s1 = ','.join(map(str, splited_line))

This should copy the data from arrowhead.txt to output.txt . Test this and see if it works for what you are trying to do.

with open('arrowhead.txt', 'r') as read_file:
    with open('output.txt', 'w') as out_file:
        for row in read_file:
            out_file.write(row)

It is much easier to use Pandas for this task and will create an identical copy of your text in a file name 'test_copy.csv'. Here's the code:

import pandas as pd
df = pd.read_csv('test.csv')
df.to_csv('test_copy.csv', index=False)

Note: if you didn't install pandas you can install it using pip install pandas

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