如何将列表的列表转换为 python 中的字符串?
How to convert a list of list to a string in python?
我有一个从文本文件中读取的列表 'arrowhead.txt',它是字符串。我想读取字符串并将其再次写入 python 中的另一个文本文档。
我知道我可以将文本从输入文件复制到目标文件,但我需要为此使用 python。
有什么帮助吗?
输入文件:
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
输出文件应采用相同的格式。需要帮助!
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))
这应该将数据从 arrowhead.txt
复制到 output.txt
。对此进行测试,看看它是否适用于您正在尝试做的事情。
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)
使用 Pandas 完成此任务要容易得多,并且会在文件名 'test_copy.csv' 中创建与您的文本完全相同的副本。这是代码:
import pandas as pd
df = pd.read_csv('test.csv')
df.to_csv('test_copy.csv', index=False)
注意:如果您没有安装 pandas,您可以使用 pip install pandas
安装
我有一个从文本文件中读取的列表 'arrowhead.txt',它是字符串。我想读取字符串并将其再次写入 python 中的另一个文本文档。 我知道我可以将文本从输入文件复制到目标文件,但我需要为此使用 python。 有什么帮助吗? 输入文件:
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
输出文件应采用相同的格式。需要帮助!
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))
这应该将数据从 arrowhead.txt
复制到 output.txt
。对此进行测试,看看它是否适用于您正在尝试做的事情。
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)
使用 Pandas 完成此任务要容易得多,并且会在文件名 'test_copy.csv' 中创建与您的文本完全相同的副本。这是代码:
import pandas as pd
df = pd.read_csv('test.csv')
df.to_csv('test_copy.csv', index=False)
注意:如果您没有安装 pandas,您可以使用 pip install pandas
安装