【问题标题】:Write text file to specific column in CSV file将文本文件写入 CSV 文件中的特定列
【发布时间】:2017-07-14 14:37:31
【问题描述】:

我有一个文本文件,我想将其内容写入 CSV 文件中的特定列。 这是我的代码

import csv
f1 = open ("input.txt","r") # open input file for reading
f = f1.read()

with open('output.csv','w') as csvfile: # input csv file
            a = csv.writer(csvfile, delimiter=',')

              # edit the 8th column
            a.writerow(str(f))
f1.close()

输入.txt: 这是文件一

我的问题是它在一行中写入每个字母而不是整个句子,我如何分配给特定列(如 row[0])以获取内容。

output.csv(r means row)
r1 r2 r3 r4     r5 r6  r7  r8  r9  r10  r11  r12  r13
T  H   I  S     I  S   F    I  L   E     O    N    E

【问题讨论】:

  • 请展示input.txt 的内容示例以及您希望out.csv 的外观。
  • 我编辑了问题并包含了一个示例。
  • 是行还是列?
  • 对不起,你是对的,它是列。 .那是因为我将 writerow 更改为 writerows 并将每个字母排成一行......但我想要唯一的行 [0]
  • @YousraGad,你是说T,H,I,S, ,I,S, ,F,I,L,E, ,O,N,E吗?因为您使用逗号作为分隔符。

标签: python python-3.x file csv


【解决方案1】:

我找到了我想要的this question related 。我编辑了我的代码,它运行良好:

import csv
row = []
f1 = open ("input.txt","r") # open input file for reading
file = f1.read()
row.append(file)

with open('output.csv','w', newline='') as csvfile: # input csv file
            a = csv.writer(csvfile,delimiter=',', quoting=csv.QUOTE_MINIMAL)
            for i in row:

                     a.writerow([i])
f1.close() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多