Answer the question
In order to leave comments, you need to log in
Error while working with files. What is the problem and how to fix it?
Hi all! I just started learning Python 3, learning the theory and doing the simplest things in practice.
So far, I'm learning on his tutorials ( Roman Sokunov )
So, in tutorial #26 we are talking about generating first names with last names, sorting them and writing them to a file.
Since I don’t like everything to be straightforward, I’m trying to add something on my own, and I got this code:
import time, sys, random
firstname = ['Andrey', "Sasha", "Artem", "Roma"]
lastname = [" veskii"," Kross"," Lylka"]
good =[]
all = []
c = 0
a = 0
b = 0
index = 1
print("Система >> Выполняется скрипт запуска ...")
time.sleep(0.3)
print("Система >> Загрузка обновлений.")
time.sleep(0.2)
print("Система >> .... .... .... ....", random.randint(0, 25), "%")
print("Система >> .... .... .... ....", random.randint(25, 50), "%")
print("Система >> .... .... .... ....", random.randint(50, 75), "%")
print("Система >> .... .... .... .... 100 %")
print("Система >> Выгрузка данных.")
print("Система >> Оптимизация работы.")
print("Система >> Генерация трафика.")
print("Система >> ...")
print("Система >> Систама готова к использованию.")
time.sleep(0.50)
start = input("Система >> Выберите деятельность работы (введите цифру):\n1) Создание личностей\n2) Крах системы\n")
if start == "1":
time.sleep(0.5)
print('Начинаю создание личностей, типа: № Имя Фамилия.')
time.sleep(0.5)
start_name = "Лица с фамилией"
print(start_name, lastname[b] + ":")
time.sleep(0.5)
for one in lastname:
for one in firstname:
good.insert(c, firstname[a] + lastname[b])
all.insert(c, firstname[a] + lastname[b])
print(index, "".join(good))
c = c + 1
a = a + 1
index = index + 1
good = []
if a > len(firstname) - 1:
f = open ("/Users/Stas/Desktop/Python/" + lastname[b] + ".txt", 'a')
f.write(lastname[b] + '\n')
f.close()
print(lastname[b], ' = ', good)
f = open(lastname[b] + ".txt", 'w')
good = str(good)
f.write(good)
f.close()
b = b + 1
a = 0
index = 1
if b <= len(lastname) - 1:
print(start_name, lastname[b] + ":")
time.sleep(0.3)
else:
print("Создание личностей закончена.")
time.sleep(1)
print("Всего создано:", len(all), "лиц.")
time.sleep(1)
print("Конец работы.")
time.sleep(1.5)
name = input("NONAME >> Как твое имя, командос? \n")
time.sleep(0.5)
q = input("NONAME >> Ты готов к порабощению мира? \n")
if q == "Да":
time.sleep(0.5)
print("NONAME >>", name.capitalize(), ", я рад. Создания спец. отряда началось.")
elif q == "да":
time.sleep(0.5)
print("NONAME >>", name.capitalize(), ", я рад. Создания спец. отряда началось.")
elif q == "Нет":
time.sleep(0.5)
print("NONAME >>", name.capitalize(), ", я огорчен твоим ответом. Я вынужден принять крайниее меры.")
time.sleep(2)
error = "[ERROR] >> 502. 0x106c670e0 \n"
print(error * 50)
print("HACK >> Взлом .... .... .... ....",random.randint(0, 25),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... ....",random.randint(25, 50),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... ....",random.randint(50, 75),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... .... 100 %")
time.sleep(0.3)
print("NONAME >> Желаю успехов, а мне нужно идти.")
elif q == "нет":
time.sleep(0.5)
print("NONAME >>", name.capitalize(), ", я огорчен твоим ответом. Я вынужден принять крайниее меры.")
time.sleep(2)
error = "[ERROR] >> 502. 0x106c670e0 \n"
print(error * 50)
print("HACK >> Взлом .... .... .... ....",random.randint(0, 25),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... ....",random.randint(25, 50),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... ....",random.randint(50, 75),'%')
time.sleep(0.1)
print("HACK >> Взлом .... .... .... .... 100 %")
time.sleep(0.3)
print("NONAME >> Все данные выкачены. Желаю успехов, а мне нужно идти.")
if start == "2":
time.sleep(0.5)
print("Систем >> Запущен процесс очистки. rm -rf")
time.sleep(2)
error = "[ERROR] >> 502. 0x106c670e0 \n"
print(error * 50)
time.sleep(0.3)
print("Система >> Все данные были удалены. Выполняю reboot.")
Начинаю создание личностей, типа: № Имя Фамилия.
Лица с фамилией veskii:
1 Andrey veskii
2 Sasha veskii
3 Artem veskii
4 Roma veskii
veskii = []
Лица с фамилией Kross:
Traceback (most recent call last):
File "/Users/Stas/Desktop/Python/script3 (names1).py", line 34, in <module>
good.insert(c, firstname[a] + lastname[b])
AttributeError: 'str' object has no attribute 'insert'
f = open ("/Users/Stas/Desktop/Python/" + lastname[b] + ".txt", 'a')
f.write(lastnames[b] + '\n')
f.close()
print(lastnames[b], ' = ', good)
f = open(lastnames[b] + ".txt", 'w')
good = str(good)
f.write(good)
Answer the question
In order to leave comments, you need to log in
bro, let's learn Python and not copy-paste
your own function / method,
display it before inserting and understand why the variable suddenly turned out to be a string and not a list, here you can read the list methods at the same time
pythonworld.ru/tipy-dannyx-v-python/spiski-list -fu...
PS Russian is written to files perfectly, in the third Python it is necessary to apply decode, and it is even better to write to a file, but in binary mode
If anyone is interested, then I redid this code (more precisely, I completely shoveled it: D)
Материал:
Завершение первой версии генератора
firstnames = ['Anthony', 'Timothy']
lastnames = ['Smith', 'Parker']
temporarylist = []
i = 0
b = 0
c = 0
for item in lastnames:
for item in firstnames:
temporarylist.insert(c, firstnames[i] + lastnames[b])
i = i + 1
c = c + 1
if i > len(firstnames) - 1:
# Now writing current family name to Families.txt
file = open("listoffamilies.txt", 'a')
file.write(lastnames[b] + '\n')
file.close()
# Now writing chain of cyborg-names to Smith.txt, Parker.txt etc.
print(lastnames[b], ' = ', temporarylist)
file = open(lastnames[b] + ".txt", 'w')
temporarylist = str(temporarylist)
file.write(temporarylist)
file.close()
b = b + 1
i = 0
c = 0
did Roman Sokunov teach you how to iterate over a list and access elements by index?
# bad
b = 0
for item in lastnames:
lastname = lastnames[b]
b = b + 1
print(lastname)
# good
for lastname in lastnames:
print(lastname)
firstnames = ['Andrey', "Sasha", "Artem", "Roma"]
lastnames = [" veskii"," Kross"," Lylka"]
# можно так
for lastname in lastnames:
with open('{}.txt'.format(lastname), 'w') as f:
for i, firstname in enumerate(firstnames):
f.write('{} {} {}\n'.format(i, firstname, lastname))
# или так
names = dict((lastname, firstnames) for lastname in lastnames)
for lastname, names_list in names.items():
with open('{}.txt'.format(lastname), 'w') as f:
f.write(
'\n'.join(
'{} {} {}'.format(i, firstname, lastname) for i, firstname in enumerate(names_list)
)
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question