'Read from text and write to csv Python
I want to write the data I read from the .text to the csv file. Maybe like a simple problem for yours but I don't handle it
- The csv file will have two headers.
- What I read from text will be written in the first heade, and a static data (e.g. city name) will be entered automatically in the second header.
Sample can be reproduced, the text inside the .text file is as follows:
John Smith,Accounting,November
Erica Meyers,IT,March
The csv file is as below;
------------------------------------------
|information | city |
------------------------------------------
|John Smith,Accounting,November | London |
------------------------------------------
|Erica Meyers,IT,March | Granada|
------------------------------------------
I tried to use writer.Writeheader but I had to use Dictwriter. It didn't solve my problem.
I create a object like follows:
header = ["information", "city"]
This code works but doesn't do what I want
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
