【问题标题】:Read output of a csv file and write it to a text file using Python读取 csv 文件的输出并使用 Python 将其写入文本文件
【发布时间】:2017-10-03 17:04:43
【问题描述】:

我有一个 python 文件,我在其中获取学生数据库的用户输入,并将它们写为 csv 文件。我无法在 google 中获取链接来读取 csv 输出并将这些 csv 输出写入文本文件。

示例 Csv 输出:

Name    Roll no Age Mark1   Mark2
a        1       2    3       4
g        3      54    54      3

导入 csv

with open('abc.csv','r') as f:
    reader=csv.dictreader(f)
    for row in reader:
        output=('xyz.txt','r')

我知道如何读取 csv 文件,但我不知道如何将这些内容写入文本文件

【问题讨论】:

  • 请先google你的问题
  • 总之,我的问题是如何读取 csv 输出并将其写入文本文件,而不是读取文本文件并将其写入 csv
  • 如果您认为您的问题是独一无二的,请提供您的代码。向我们展示您已经完成的工作。
  • 那么,你想把csv的每一行写入文本文件'xyz.txt'吗?

标签: python python-2.7 csv text


【解决方案1】:

使用下面的代码缩进和cmets是内联的

  1. 读取 CSV 文件
  2. 操作字段
  3. 写入文件

块引用

import csv

#Open file with "w"(write), the file will create automatically.
file = open("/home/xyz/testfile.txt", "w")
#Open CSV file to read CSV, note: reading and write file should be under "with"
with open('/home/xyz/Desktop/ta_cta.csv') as csvFile:
    #Read CSV
    readCsv = csv.reader(csvFile)
    for row in readCsv:
        #Get Values and manupilate in the file.write
        Id = row[0]
        Id1 = row[1]
        #Write CSV you need format it to string if the value is an int
        file.write("UPDATE Schema.TableName SET Column1="+str(Id1)+" where Column2="+str(Id)+";\n")
#You Must Close the FIle after writing it.
file.close()

【讨论】:

    【解决方案2】:

    你可以试试这个代码:

    import csv
    
    output=open('xyz.txt','w')
    
    with open('abc.csv',"rt", encoding='ascii') as f:
    for row in f:
        output.write(row)
    

    【讨论】:

    • 需要使用 For 循环。我的文件不需要 Ascii 编码。请编辑它们。
    • 您能解释一下为什么您将模式指定为 rt 和 ascii 编码吗?我可以理解其余的代码。对不起,我是python的初学者
    • 当然,但我打赌你可以用谷歌搜索,你的问题的答案在这里:stackoverflow.com/questions/23051062/…
    • 关于,ascii编码,以防万一,也许你会用到。
    • 谢谢 :) 当我选择一个特定的卷号时,如何获取 csv 文件中整行的内容?
    【解决方案3】:

    你应该先学习python csv模块。

    https://docs.python.org/2/library/csv.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多