【发布时间】:2021-02-04 21:41:53
【问题描述】:
我是 Python 新手,目前正在努力完成这项任务。我暂时还不想使用高级工具(例如 pandas 或面向对象编程)来执行此操作。
我有一个 CSV 文件,我需要添加其他行。但是当我运行下面的代码时,所有值都添加到最后一行的最后一个单元格中,如下所示。
这是我的代码。我做错了什么? 导入csv
问候用户并让她输入文件名:
打印'你好' source_file = str(input('请输入名册文件:'))
name_counter = 1
要求正确的文件名
csv_input = open(source_file, 'a')
询问您是否要添加其他名称
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 文件中。换句话说,我想做以下事情:
- 读取 CSV 文件
- 向 CSV 文件添加行
- 将生成的包含新行的 CSV 文件保存为 TXT 文件,但保持原始 CSV 文件不变
- 所以最后我会得到 original.csv 文件和一个新的 original_expanded.txt
【问题讨论】:
-
为什么要使用
{:10s}等格式打印值?而不是简单的值,后跟逗号?显然你需要一两个换行符。更好的是,如果可以的话,使用csv包。 -
CSV 文件的新行在哪里?