【问题标题】:How to convert a list of list to a string in python?如何将列表列表转换为python中的字符串?
【发布时间】:2020-01-29 03:08:41
【问题描述】:

我有一个从文本文件“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))

【问题讨论】:

  • 你能展示你用来从第一个文件中读取数据的代码吗?
  • 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)) 我对这一步之后该怎么做感到困惑。

标签: python arrays python-3.x list file-read


【解决方案1】:

使用 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 安装它

【讨论】:

    【解决方案2】:

    这应该将数据从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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 2021-11-10
      • 2017-04-10
      • 2019-07-31
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多