我想将从.text读取的数据写入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] 删除。
我来说两句