我想将从.text读取的数据写入csv文件。也许对你来说是个简单的问题,但我不处理
。
可以复制示例,.text文件中的文本如下:
John Smith,Accounting,November
Erica Meyers,IT,Marchcsv文件如下;
------------------------------------------
|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)发布于 2021-01-24 00:53:45
您可以使用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)https://stackoverflow.com/questions/65864291
复制相似问题