读取csv文件的输出并使用Python将其写入文本文件

时间:2017-05-05 09:20:27

标签: python python-2.7 csv text

我有一个python文件,我获取学生数据库的用户输入,我已将它们写为csv文件。我无法在谷歌中获取链接以读取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文件,但我不知道如何将这些内容写入文本文件

3 个答案:

答案 0 :(得分:2)

使用以下代码缩进和注释是内联的

  1. 阅读CSV文件
  2. 操纵字段
  3. 写入文件
  4.   

    块引用

    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()
    

答案 1 :(得分:0)

你应该首先学习python csv模块。

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

答案 2 :(得分:0)

你可以试试这段代码:

import csv

output=open('xyz.txt','w')

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