首页 > 解决方案 > 将行添加到 CSV 文件并将生成的 CSV 保存为 TXT 并保持原始 CSV 不变

问题描述

我是 Python 新手,目前正在努力完成这项任务。我还不想使用高级工具(例如 pandas 或面向对象编程)来完成此操作。

我有一个 CSV 文件,我需要添加其他行。但是当我在下面运行代码时,所有值都添加到最后一行的最后一个单元格中,如下所示。

输出

这是我的代码。我做错了什么?导入 csv

问候用户并让她输入文件名:

print 'Hello' source_file = str(input('请输入名册文件:'))

name_counter = 1

要求正确的文件名

csv_input = open(source_file, 'a')

询问 uer 是否要添加其他名称

name_bool =
str(input('你想输入其他名字吗?(Y/N):'))

如果 name_bool == 'Y':

number_names = int(input('How many more names? '))  # The number of additional people to add

while name_counter <= number_names:
    first_name = str(input('First name: '))
    csv_input.write('{:10s}'.format(first_name, end=' '))

    last_name = str(input('Last Name: '))
    csv_input.write('{:10s}'.format(last_name, end=' '))

    person_age = str(input('Age: '))
    csv_input.write('{}'.format(int(person_age), end=' '))

    person_occupation = str(input('Occupation: '))
    csv_input.write('{:10s}'.format(person_occupation, end=' '))

    person_height = str(input('Height (in inches): '))
    csv_input.write('{}'.format(int(person_height), end=' '))

    person_weight = str(input('Weight (in pounds): '))
    csv_input.write('{}'.format(int(person_weight), end=' '))

    print '\n'

    name_counter = name_counter + 1

elif name_bool == 'N':

    # Close the file when we are done adding

print 'You are done'

csv_input.close()

感谢大家的回答,我能够解决我原来的问题。

但是我想保持原始 CSV 文件不变。我想将其他行添加到新 TXT 文件中的 CSV 文件中。换句话说,我想做以下事情:

  1. 读取 CSV 文件
  2. 向 CSV 文件添加行
  3. 将包含新行的生成的 CSV 文件另存为 TXT 文件,但保持原始 CSV 文件不变
  4. 所以最后我会得到 original.csv 文件和一个新的 original_expanded.txt

标签: pythoncsvfile-io

解决方案


尝试这个:

print ('Hello')
source_file = str(input('Please enter a roster file: '))
csv_input = open(source_file, 'a')
name_bool = str(input('Would you like to enter additional names? (Y/N): '))
if name_bool == 'Y':
    name_counter = 1
    number_names = int(input('How many more names? '))  # The number of additional people to add
    csv_input.write("\n")
    while name_counter <= number_names:
        first_name = str(input('First name: '))
        csv_input.write(first_name + ", ")

        last_name = str(input('Last Name: '))
        csv_input.write(last_name + ", ")

        person_age = str(input('Age: '))
        csv_input.write(person_age + ", ")

        person_occupation = str(input('Occupation: '))
        csv_input.write(person_occupation + ", ")

        person_height = str(input('Height (in inches): '))
        csv_input.write(person_height + ", ")

        person_weight = str(input('Weight (in pounds): '))
        csv_input.write(person_weight + "\n")

        print ('\n')

        name_counter = name_counter + 1
elif name_bool == 'N':
    print('You are done')

csv_input.close()

推荐阅读