【问题标题】:converting TXT to CSV python将TXT转换为CSV python
【发布时间】:2018-04-30 13:26:12
【问题描述】:

我有一个 txt 数据。它看起来如下

time pos
0.02 1
0.1 2
 ...

等等。所以每一行都用空格隔开。我需要将其转换为 CSV 文件。喜欢

time,pos
0.02,1
0.1,2
0.15,3

我怎样才能用 python 做到这一点?这是我尝试过的

time = []
pos = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader)
        for row in csvFileReader:
            time.append((row[0].split(' ')[0]))
            pos.append((row[1]))
    return

【问题讨论】:

  • 你的代码有什么问题?
  • 您的文件是否有任何包含空格的引用参数?如果没有,只做line.replace(' ', ',')就足够了吗?

标签: python csv


【解决方案1】:
with open(filename) as infile, open('outfile.csv','w') as outfile: 
    for line in infile: 
        outfile.write(line.replace(' ',','))

【讨论】:

  • 谢谢,更多pythonic :D
  • 你必须在每一行的末尾附加\n
  • 与您的新编辑'_io.TextIOWrapper' object has no attribute 'writeline'
  • 我把语言弄混了。它应该像现在一样工作。
【解决方案2】:

来自here

import csv
with open(filename, newline='') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        print(row)

对于写作只使用默认选项,它会用逗号作为分隔符保存文件。

【讨论】:

    【解决方案3】:

    尝试:

    import pandas as pd
    with open(filename, 'r') as fo:
        data = fo.readlines()
        for d in range(len(data)):
            if d==0:
                column_headings = data[d].split()
            data_to_insert = data[d].split()
            pd.DataFrame(data_to_insert).to_excel('csv_file.csv', header=False, index=False, columns = column_headings))
    

    【讨论】:

    • TypeError: writelines() 只接受一个参数(给定 0)
    【解决方案4】:

    你可以用这个:

    import csv
    time = []
    pos = []
    
    def get_data(filename):
        with open(filename, 'r') as csvfile:
            csvfile1 = csv.reader(csvfile, delimiter=' ')
            with open(filename.replace('.txt','.csv'), 'w') as csvfile:
                writer = csv.writer(csvfile, delimiter=',')
                for row in csvfile1:
                    writer.writerow(row)
    

    【讨论】:

      猜你喜欢
      • 2017-01-31
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多