[英]Read csv lines and save it as seperate txt file, named as a line - python
i have some problem with simple code. 我有一些简单的代码问题。 I have a csv file with one column, and hundreds rows.
我有一个带有一栏和几百行的csv文件。 I would like to get a code to read each line of csv and save it as separate txt files.
我想获得一个代码来读取csv的每一行并将其另存为单独的txt文件。 What is important, the txt files should have be named as read line.
重要的是,txt文件应已命名为读取行。
Example: 1.Adam 2. Doroty 3. Pablo 例如:1.亚当2.多罗蒂3.巴勃罗
will give me adam.txt, doroty.txt and pablo txt. 会给我adam.txt,doroty.txt和pablo txt。 files.
文件。 Please, help.
请帮忙。
This should do what you need on python 3.6 这应该在python 3.6上做您需要的
with open('file.csv') as f: # Open file with hundreds of rows
for name in f.read().split('\n'): # Get list of all names
with open(f'{name.strip()}.txt', 'w') as s: # Create file per name
pass
Alternatively you can use built-in CSV library to avoid any complications with parsing csv files: 另外,您可以使用内置的CSV库来避免解析csv文件带来的任何麻烦:
import csv
with open('names.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
file_name ='{0}.txt'.format(row['first_name'])
with open(file_name, 'w') as f:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.