#python #csv
#python #csv
Вопрос:
Это мой код
import csv
with open('dane_d.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count = 1
else:
print(f't{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]}{row[6]},{row[7]},{row[8]},{row[9]}.')
with open('%s.txt'%row[0], mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow("{0}{1},{2},{3},{4},{5},{6},{7},{8},{9}".format(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9]))
входной файл
WHH,D,20200911,000000,0.384,0.454,0.384,0.43,22,0
WHH,D,20200911,000000,9.75,9.75,9.75,9.75,52,0
11B,D,20200813,000000,492.5,507,490.5,506,2722,0
вывод
W,H,H,D,",",2,0,2,0,0,9,1,1,",",0,0,0,0,0,0,",",0,.,3,8,4,",",0,.,4,5,4,",",0,.,3,8,4,",",0,.,4,3,",",2,2,",",0
W,H,H,D,",",2,0,2,0,0,9,1,1,",",0,0,0,0,0,0,",",9,.,7,5,",",9,.,7,5,",",9,.,7,5,",",9,.,7,5,",",5,2,",",0
Ответ №1:
csv.writer.writerow
ожидает список переменных, а не строку, разделенную запятыми.
import csv
with open('dane_d.txt') as csv_file, open('%s.txt'%row[0], mode='a', newline='') as file:
csv_reader = csv.reader(csv_file, delimiter=',')
writer = csv.writer(file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count = 1
else:
print(f't{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]}{row[6]},{row[7]},{row[8]},{row[9]}.')
writer.writerow(row)
Ответ №2:
Попробуйте использовать с open и file.напишите, чтобы записать в файл.
Пример:
import csv
with open('dane_d.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
print (row)
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count = 1
else:
print(f't{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]}{row[6]},{row[7]},{row[8]},{row[9]}.')
with open('%s.txt'%row[0], mode='a', newline='') as file:
file.write("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}".format(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9]))
Комментарии:
1. это те же 1,1, B,D,2,0,2,0,0,8,1,3,0,0,0,0,0,0,4,9,2,.,5,5,0,7,4,9,0,.,5,5,0,6,2,7,2,2,0 я думаю, что проблема в writerow, но я новичок и не знаю, что мне следует использовать
2. Попробуйте использовать с open для записи в файл, код обновлен выше
Ответ №3:
закрыть сообщение
ответ я использую это
file.write("n{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}".format(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9]))
и его работа