【问题标题】:Python 3: Attempting to iterate thru csv file and write contents to text filePython 3:尝试遍历 csv 文件并将内容写入文本文件
【发布时间】:2020-10-12 20:32:48
【问题描述】:

我正在尝试读取下面 csv 文件的每一行。

csv file

我想从每一行中提取数据并附加到一个新的文本文件中。

这是我用来读取 csv 文件的代码:

#Count number of lines in the csv file
cnd = datetime.now().strftime("%m%d%y")
df = pd.read_csv(cnd+'sr.csv')
numline = len(df)
ma = df['Make'][:numline]
mo = df['Model'][:numline]
yr = df['Year'][:numline]
cl = df['Color'][:numline]
pr = df['Price'][:numline]


#For loop to break the csv file into 10 lines at a time
for x in range(0,numline,10):
    if x < 10:
        mk = ma[:10]
        mod = mo[:10]
        ye = yr[:10]
        clr = cl[:10]
        prc = pr[:10]

我正在使用下面代码的 sn-p 来创建新的文本文件,从 csv 文件中提取数据并将数据附加到新的文本文件中。问题出在第三个代码块上。

#Create text File
facts = datetime.now().strftime("%m-%d-%y-%H%M%S.txt")
f = open(facts, 'w+')

#Write generic Title
f.write('Car Facts' + '\r')
f.close()                     
            
#Open the text file. Iterate thru each line of the csv file and append to the text file
of = open(facts, "a")
    for k in mk:
        for m in mod:
            for y in ye:
                for c in clr:
                    for p in prc:
                         of.write('\r' + 'Make: ' + str(k) + '\r' + 'Model: ' + str(m) + '\r' + 'Year: ' + str(y) + '\r' + 'Color: ' + str(c) + '\r' + 'Price: ' + str(p) + '\r')       
of.close()

我最终得到一个包含大约 30 个随机组合块的文本文件。 写入文本文件的第一个和最后一个块是正确的。 两者之间的其他一切都是我不需要的随机组合。

我怎样才能修复代码以获得下面想要的最终结果?

谢谢

Car Facts

Make: Ford
Model: Bronco
Year: 1978
Color: Blue
Price: $24,000.00

Make: Land Rover
Model: Defender
Year: 1985
Color: Black
Price: $21,000.00

【问题讨论】:

  • 阅读this article 了解调试代码的技巧。
  • 您在哪里阅读您的 csv 文件? mk/mod/ye/clr/prc 未在您的 sn-p 中定义。
  • 我假设这些变量是集合。试试zip函数:for data in zip(mk,mod,ye,clr,prc): print(data)
  • 嗨马克西米利安。这是我用来读取 csv 文件的 sn-p:
  • #计算csv文件行数 cnd = datetime.now().strftime("%m%d%y") df = pd.read_csv(cnd+'sr.csv') numline = len(df) ma = df['Make'][:numline] mo = df['Model'][:numline] yr = df['Year'][:numline] cl = df['Color'][ :numline] pr = df['Price'][:numline] #For循环将csv文件一次分成10行 for x in range(0,numline,10): if x

标签: python python-3.x csv


【解决方案1】:

这会打开现有的 CSV 文件并在将行写入新文本文件时循环遍历它。您可能必须手动删除第一个条目,因为它包含标题

File1 = open("Existing CSV File.csv", "r")
File2 = open("New text file.txt", "w")
for X in File1:
    Line = X.split(",")
    File2.write("Make: " + Line[0] + "\n")
    File2.write("Model: " + Line[1] + "\n")
    File2.write("Year: " + Line[2] + "\n")
    File2.write("Colour: " + Line[3] + "\n")
    File2.write("Price: " + Line[4] + "\n")
    File2.write("")
File1.close()
File2.close()

【讨论】:

  • Line 已经是字符串列表,无需转换。输出也不同于 OP 的期望输出。
  • @MaximilianPeters 这样更好吗?
  • 谢谢 Evorage,输出需要进一步的工作。
  • 嗨,Evorage,我从星期六晚上就一直在这。您的建议是帮助解决我的问题的突破。即,您使用 Line[x] 来编写输出。我从来没有想过使用 Line[x] 来编写输出。非常感谢您的意见。谢谢
  • @jiro 没问题,这就是 stackoverflow 的用途
猜你喜欢
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多