【问题标题】:Read from text and write to csv Python从文本读取并写入 csv Python
【发布时间】:2021-04-28 01:11:32
【问题描述】:

我想将从 .text 读取的数据写入 csv 文件。也许对你来说是一个简单的问题,但我不会处理它

  • csv 文件将有两个标题。
  • 我从文本中读取的内容将写入第一个标题,而静态数据(例如城市名称)将自动输入第二个标题。

可以复制样例,.text文件里面的文字如下:

John Smith,Accounting,November
Erica Meyers,IT,March

csv文件如下;

------------------------------------------
|information                    | city   |
------------------------------------------
|John Smith,Accounting,November | London | 
------------------------------------------
|Erica Meyers,IT,March          | Granada|
------------------------------------------

我尝试使用writer.Writeheader,但我不得不使用Dictwriter。它没有解决我的问题。

我创建如下对象:

header = ["information", "city"] 

此代码有效,但不符合我的要求

with open('employee.txt', mode='r') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=',')

    line_count = 0
    with open('aa.csv', 'w') as out_file:
        for row in csv_reader:
           if line_count == 0:
               for column in row:
                   out_file.write('%s;' % column)
               out_file.write('\n')
               line_count += 1
           else:
               for column in row:
                   out_file.write('%s;' %column)
               out_file.write('\n')
               line_count += 1
        print(line_count)

【问题讨论】:

  • 您显示为“文本”文件的内容实际上是 CSV 格式,而您显示为“csv”文件的内容不是。
  • 嗯,我的输出应该是这样的,就像标签一样
  • 如果您将标题从“信息、城市”更改为“姓名、部门、​​月份、城市”,您的任务会更轻松。 CSV 文件喜欢用逗号分隔列。
  • 你说得对,csv 想要带逗号的数据,但是我想把我从文本中读到的内容写成两个不同的列中的 2 个不同的标题,我该怎么做,谢谢你宝贵的 cmets

标签: python csv write


【解决方案1】:

您可以使用pandas 模块来执行此操作。

import pandas as pd

with open('employees.txt', 'r') as inFile:

    # Read the text file in as a list of lines using .readlines()
    employees = inFile.readlines()
    
    # Strip newline characters ('\n') from each line
    employees = [x.strip('\n') for x in employees]

    # Add city to each line
    employees = [[x, 'city'] for x in employees]


header = ["information", "city"]

# Create a DataFrame
df = pd.DataFrame(employees, columns=header)

# Write the dataframe to a csv
df.to_csv('aa.csv', header=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多