JavaScript
x
59
59
1
import random
2
3
4
def main():
5
6
print('Program will create a trial database.')
7
print()
8
9
#polish names and surnames
10
11
all_names = [name.rstrip() for name in open('names.txt', encoding='utf-8').readlines()]
12
women_names = [name for name in all_names if name.endswith('a')]
13
14
all_surnames = [name.rstrip() for name in open('surname.txt', encoding='utf-8').readlines()]
15
16
women_surnames = [sname for sname in all_surnames if not sname.endswith('ski') and not
17
sname.endswith('cki') and not sname.endswith('sny') and not
18
sname.endswith('zki')]
19
20
men_surnames = [sname for sname in all_surnames if not sname.endswith('ska') and not
21
sname.endswith('cka') and not sname.endswith('zka') and not
22
sname.endswith('sna')]
23
24
cities = [city.rstrip() for city in open('cities.txt', encoding='utf-8').readlines()]
25
26
def record():
27
"""Function creates records based on file input."""
28
while True:
29
try:
30
num_records = int(input("Enter the number of records: "))
31
break
32
except ValueError:
33
print('Invalid value! Try again...')
34
35
database = []
36
for i in range(1, num_records + 1):
37
name_choice = random.choice(all_names)
38
if name_choice in women_names:
39
sname_choice = random.choice(women_surnames)
40
else:
41
sname_choice = random.choice(men_surnames)
42
city_choice = random.choice(cities)
43
database.append([name_choice, sname_choice, city_choice])
44
45
46
def save_data():
47
name_file = input('Enter the name of the text file [name.txt]: ')
48
data = open(name_file, 'w', encoding='utf=8')
49
data.write(str(database))
50
data.close()
51
print(f'Records were create in the file: {name_file}.')
52
save_data()
53
record()
54
55
56
57
if __name__ == '__main__':
58
main()
59
I receivng: name_file.txt
JavaScript
1
4
1
1.[[name, surname, city], [name1, surname1, city1], ]
2
2.
3
3.
4
I can’t find a way to get every record on a new line… like this:
JavaScript
1
4
1
1. [name, surname, city],
2
2. [name1, surname1, city1],
3
3. [name2, surname2, city2],
4
or better:
JavaScript
1
4
1
1. name, surame, city
2
2. name1, surname1, city1
3
3. name2, surname2, city2
4
Advertisement
Answer
Update your save_data
function like this. You need to format generate output string from database
array before writing into file.
JavaScript
1
10
10
1
def save_data():
2
name_file = input('Enter the name of the text file [name.txt]: ')
3
data = open(name_file, 'w', encoding='utf=8')
4
# generate formatted output
5
output_str = "n".join(map(lambda s : ", ".join(s), database))
6
# write formatted output
7
data.write(output_str)
8
data.close()
9
print(f'Records were create in the file: {name_file}.')
10