S
S
Stas Kross2016-02-28 21:38:12
Python
Stas Kross, 2016-02-28 21:38:12

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.")

The problem comes up like this:
Начинаю создание личностей, типа: № Имя Фамилия.
Лица с фамилией  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'

If we remove this piece of code:
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)

Then everything works like clockwork, as I planned, namely, faces of the type are created:
What surname:
No. First name Last name
Another surname:
No. First name Last name (The number in each surname starts with 1)
and so on ..
So, the point is this:
It is necessary to make the creation of names from the list (firstname & lastname) names with a surname, which will be numbered and separated from each other (code above) + writing to a file, namely, that a file with a surname would be created, and it would be written there like this:
No. Name Surname
№ First name Last name
And so on...
Then, when switching to another last name, another file was created, with the name of the new last name, and new data was written there.
Lots and lots of text, sorry, but I just can't figure out why it's not working! What's wrong!
For help, I will be very grateful to you! Thank you!
PS Why can't Python write Russian text to files?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2016-02-28
@dimonchik2013

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

S
Stas Kross, 2016-02-28
@BrainRTP

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

What is wrong with this code? It doesn't work either... Either I'm very tired, and my head doesn't cook, and all this is hallucination.

A
angru, 2016-02-29
@angru

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)

and you can also discover the enumerate function
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 question

Ask a Question

731 491 924 answers to any question