Запись каждого элемента массива в отдельный файл
Мне нужно, чтобы 1й элемент массива записывался в 1й файл в папке, 2й элемент в 2й файл и т.д. Этот код записывает только 1й элемент во все созданные файлы.
mypath = "C:/Users/dexp/Desktop/songs beatstar/songs/"
with open("C:/Users/dexp/Desktop/songs beatstar/name_songs.txt") as file_in:
lines = []
for line in file_in:
lines.append(line.rstrip())
with open("C:/Users/dexp/Desktop/songs beatstar/score_songs.txt") as file_in1:
scores = []
for line1 in file_in1:
scores.append(line1.rstrip())
print(lines)
print(scores)
for file in lines:
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
f.write(scores[0])
Ответы (2 шт):
Автор решения: Сергей
→ Ссылка
Откорректированы 3 строки с комментариями - проверьте. Полностью согласен с комментарием @n1tr0xs, что не менялся элемент массива.
mypath = "C:/Users/dexp/Desktop/songs beatstar/songs/"
with open("C:/Users/dexp/Desktop/songs beatstar/name_songs.txt") as file_in:
lines = []
for line in file_in:
lines.append(line.rstrip())
with open("C:/Users/dexp/Desktop/songs beatstar/score_songs.txt") as file_in1:
scores = []
for line1 in file_in1:
scores.append(line1.rstrip())
print(lines)
print(scores)
# Вводим счетчик
i = 0
for file in lines:
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
# модифицируем номер
f.write(scores[i])
# Увеличиваем счетчик
i += 1
Автор решения: n1tr0xs
→ Ссылка
- Вы не меняете номер элемента, который записываете. Есть несколько вариантов как это исправить (вариант Сергея повторять, думаю не стоит):
#1 - list.pop() (не рекомендую использовать)
for file in lines:
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
f.write(scores[0])
scores.pop(0)
#2 range(len(list))
for i in range(len(lines)):
FileFullPath = os.path.join(mypath, lines[i])
with open(FileFullPath, 'w') as f:
f.write(scores[i])
#3 - zip(list, list)
for file, score in zip(lines, scores):
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
f.write(score)
#4 - enumerate(list). Спасибо Эдуард Измалков за идею
for i, file in enumerate(lines):
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
f.write(scores[i])
- Если у вас есть переменная путей к файлам, то лучше используйте её, а не "хардкодьте" значения:
mypath = "C:/Users/dexp/Desktop/songs beatstar/songs/"
with open(os.path.join(mypath, 'name_songs.txt'))
with open(os.path.join(mypath, 'score_songs.txt'))
- Читать файлы лучше так (код короче, при этом ясность кода не теряется):
with open(os.path.join(mypath, 'name_songs.txt')) as f:
lines = [line.rstrip() for line in f]
with open(os.path.join(mypath, 'score_songs.txt')) as f:
scores = [line.rstrip() for line in f]
Есть еще такой вариант, но он может оказаться трудным для восприятия:
with open(os.path.join(mypath, 'name_songs.txt')) as f:
lines = list(map(str.rstrip, f))
with open(os.path.join(mypath, 'score_songs.txt')) as f:
scores = list(map(str.rstrip, f))
На выходе получаем:
mypath = "C:/Users/dexp/Desktop/songs beatstar/songs/"
with open(os.path.join(mypath, 'name_songs.txt')) as f:
lines = [line.rstrip() for line in f]
with open(os.path.join(mypath, 'score_songs.txt')) as f:
scores = [line.rstrip() for line in f]
print(lines)
print(scores)
for file, score in zip(lines, scores):
FileFullPath = os.path.join(mypath, file)
with open(FileFullPath, 'w') as f:
f.write(score)