【问题标题】:Read csv lines and save it as seperate txt file, named as a line - python读取 csv 行并将其保存为单独的文本文件,命名为一行 - python
【发布时间】:2017-11-02 05:31:57
【问题描述】:

我对简单的代码有一些问题。 我有一个包含一列和数百行的 csv 文件。我想获得一个代码来读取每行 csv 并将其保存为单独的 txt 文件。重要的是,txt 文件应该被命名为读取行。

示例: 1.亚当 2.多罗蒂 3. 巴勃罗

会给我adam.txt、dority.txt和pablo txt。文件。请帮忙。

【问题讨论】:

  • 请向我们展示您到目前为止所做的尝试。
  • 使用 csv 模块读取 csv 文件。 CSV 模块将解决您的问题。检查此链接docs.python.org/2/library/csv.html
  • 你也可以使用pandas 来处理csv文件。
  • 欢迎来到 Stack Overflow!你会在这里找到一些帮助,但这不是免费的代码编写服务......所以规则要求你在提出问题之前进行一些研究,展示你尝试过的内容并解释你遇到的问题。您将在How to Ask 找到更多关于什么是正确问题的解释。您真的应该阅读它...
  • 我尝试了一些东西,但是我很初学者

标签: python csv readlines


【解决方案1】:

这应该可以满足您在 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

【讨论】:

  • 因为只有1列可以直接迭代文件对象for name in f我认为没有必要使用split()。如果我错了,请纠正我
  • 你是对的,@akashkarothiya 由于文件是 .csv,如果事实上,问题会更改为连续的名称(Daniel、Chris、Jason),这可以很容易地扩展到该用例.
【解决方案2】:

或者,您可以使用内置的 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

【讨论】:

  • 这很好用,在我根据我的需要定制它之后。但是,现在每次运行它时,我都会收到错误:KeyError: 'user_name' 我 100% 确定第一行中有一个带有“user_name”的列。 :-(
  • 如果您的 csv 文件中没有标题行,您可以使用默认列名初始化 reader:reader = csv.DictReader(csvfile,fieldnames=['user_name'])
  • 请记住,在我的示例中,我使用“first_name”,根据您的评论,我们使用“user_name”作为列名
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 2018-08-24
  • 2021-02-13
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多