简体   繁体   English

读取csv行并将其另存为单独的txt文件,命名为行-python

[英]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.

相关问题 从 .xlsx 中的列中读取数据并使用 python 将每个数据保存为单独的 .txt 文件 - Read data from columns in .xlsx and save each one as seperate .txt file with python 如何编写 python 从名为“file1.txt”的文本文件中读取前两行 将从“file1.txt”读取的两行写入新文件“file2.txt” - How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt" 如何让python读取txt文件中的每一行并制作单独的列表? - How can I get python to read each line in a txt file and make seperate lists? 如何读取CSV或文本文件的行,循环遍历每行并保存为每行读取的新文件 - How To Read Lines of CSV or Text File, Loop Over Each Line and Save To a New File For Each Line Read 如何跳过行,直到在txt文件中找到“关键字”并将其余内容另存为csv? 蟒蛇 - How to skip lines until find the 'keyword' in txt file and save rest as csv? python Python-读取TXT文件行->数组 - Python - Read TXT File lines --> Array 使用 python 从 a.txt 文件中读取某些行 - Read in certain lines from a .txt file with python 从 csv 文件中分离出多行的 Column,并在 Python 中对它们进行排序 - Seperate a Column with multiple lines from a csv file and order them in Python 在Python中逐行读取.txt文件 - Read .txt file line by line in Python python - 逐行读取.txt文件 - python - read .txt file line by line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM