Мне интересно, может ли кто-нибудь мне помочь, я пробовал искать заранее, но не могу найти ответ:
У меня есть файл с именем info.dat, который содержит:
#
# *** Please be aware that the revision numbers on the control lines may not always
# *** be 1 more than the last file you received. There may have been additional
# *** increments in between.
#
$001,427,2018,04,26
#
# Save this file as info.dat
#
Я пытаюсь зациклить файл, получить номер версии и записать его в свой файл
with open('info.dat', 'r') as file:
for line in file:
if line.startswith('$001,'):
with open('version.txt', 'w') as w:
version = line[5:8] # Should be 427
w.write(version + '\n')
w.close()
Хотя это и дает правильную информацию, я получаю следующую ошибку:
Traceback (most recent call last):
File "~/Desktop/backup/test.py", line 4, in <module>
for line in file:
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 6281: ordinal not in range(128)
При попытке добавить следующее
with open('info.dat', 'r') as file:
for line in file:
if line.startswith('$001,'):
with open('version.txt', 'w') as w:
version = line[5:8]
# w.write(version.encode('utf-8') + '\n')
w.write(version.decode() + '\n')
w.close()
Я получаю следующую ошибку
Traceback (most recent call last):
File "~/Desktop/backup/test.py", line 9, in <module>
w.write(version.encode('utf-8') + '\n')
TypeError: can't concat str to bytes