print()命令不包含所有期望值

时间:2019-07-12 15:20:49

标签: python-3.x jupyter-notebook

我正在从.csv数据中读取数据,并希望将该数据的一部分写入输出文件。 当我执行程序并打印结果时,我将获得输入文件的完整数据集。 但是,当我再次点击print()时,仅显示输入文件的最后一行。

当我将打印结果写入另一个csv文件时,也仅传输了最后一行

基本上我是新来的,并且很难理解数据如何存储在缓存中并传递。

import csv
with open("path to the input file") as file:
    reader = csv.reader(file)
    for line in file:
        input_data = line.strip().split(";")
        print(input_data)

with open(os.path.join("path to the output file"), "w") as file1:
                    toFile = input_data
                    file1.write(str(toFile))

没有错误消息,只是没有预期的结果。我希望可以传输10行,但只有最后一行可以传输到输出.csv

谢谢您的帮助!

2 个答案:

答案 0 :(得分:0)

在每次迭代中循环csv中的行时,您会将该行的值分配给输入数据,从而覆盖先前存储在input_data中的值。

我建议类似以下内容:

import csv
with open('path to input file', 'r') as input, open('path to output file', 'w') as output:
        reader = csv.reader(input)
        for line in reader:
            ouput.write(line.strip().split(';'))

您可以在一个with子句中打开多个文件,如示例中所示。然后,对于文件中的每一行,将剥离和拆分后的字符串写入文件。

答案 1 :(得分:0)

这应该做到。您正确创建了阅读器对象,但没有使用它。我希望我的例子能更好地理解读者。

#!/usr/bin/env python

import csv
from os import linesep

def write_csv_to_file(csv_file_name, out_file_name):

    # Open the csv-file
    with open(csv_file_name, newline='') as csvfile:

        # Create a reader object, pass it the csv-file and tell it how to 
        # split up values
        reader = csv.reader(csvfile, delimiter=',', quotechar='|')

        # Open the output file
        with open(out_file_name, "w") as out_file:

            # Loop through the rows that the reader found
            for row in reader:

                # Join the row values using a comma as separator
                r = ', '.join(row)

                # Print row and write to output file
                print(r)
                out_file.write(r + linesep)

if __name__ == '__main__':
    csv_file = "example.csv"
    out_file = "out.txt"
    write_csv_to_file(csv_file, out_file)