从文本读取并写入csv Python

航海家

我想将从.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)
豆袋猫

您可以使用该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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

读取 csv 文件的输出并使用 Python 将其写入文本文件

Python:读取CSV文件并写入另一个文本文件

根据python中的条件读取csv并写入新的csv

Python CSV读取文件并选择列并写入新的CSV文件

如何加快 Python CSV 读取到 MySQL 写入的速度

读取和写入 csv 文件时出现 Python pandas 错误

for循环for循环,python,csv读取器/写入器

如何在 Python 中读取和写入 CSV 文件

读取,更改然后在python中写入csv数据

在读取/写入时保留文本格式以形成文本python pptx

python读取特定文本并转储到csv

读取csv到数组,对数组执行线性回归并根据梯度在Python中写入csv

从csv文件读取特定的列,然后使用python写入另一个CSV

读取 .csv 的内容并使用 python 将其写入另一个 .csv 文件

python文本文件在“ r +”模式下的意外读取/写入行为

如何在python中同时读取和写入文本文件?

在 Python 中,如何使用文件在其中写入字节并作为文本读取

如何使用Python在文本文件中读取和写入多个值?

如何在Python中读取和写入文本文件的多行

如何使用 Python 读取文件并将其完全写入多个文本文件?

我想在 python 中写入和读取文本文件的列表

python写入csv文件

Python逐行写入CSV

CSV写入错误-Python

在将数据帧写入/读取到CSV时出现问题-最终形状-Python

Python-脚本从JSON读取一个值并将其以CSV格式写入200次

Python:读取超过100万个小型csv文件并写入数据库

写入Excel-使用Pandas和Openpyxl读取CSV-Python

Python从文件读取和写入'ß'