如何逐行写入文件记录? PYTHON
How to write in file records line by line? PYTHON
import random
def main():
print('Program will create a trial database.')
print()
#polish names and surnames
all_names = [name.rstrip() for name in open('names.txt', encoding='utf-8').readlines()]
women_names = [name for name in all_names if name.endswith('a')]
all_surnames = [name.rstrip() for name in open('surname.txt', encoding='utf-8').readlines()]
women_surnames = [sname for sname in all_surnames if not sname.endswith('ski') and not
sname.endswith('cki') and not sname.endswith('sny') and not
sname.endswith('zki')]
men_surnames = [sname for sname in all_surnames if not sname.endswith('ska') and not
sname.endswith('cka') and not sname.endswith('zka') and not
sname.endswith('sna')]
cities = [city.rstrip() for city in open('cities.txt', encoding='utf-8').readlines()]
def record():
"""Function creates records based on file input."""
while True:
try:
num_records = int(input("Enter the number of records: "))
break
except ValueError:
print('Invalid value! Try again...')
database = []
for i in range(1, num_records + 1):
name_choice = random.choice(all_names)
if name_choice in women_names:
sname_choice = random.choice(women_surnames)
else:
sname_choice = random.choice(men_surnames)
city_choice = random.choice(cities)
database.append([name_choice, sname_choice, city_choice])
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
data.write(str(database))
data.close()
print(f'Records were create in the file: {name_file}.')
save_data()
record()
if __name__ == '__main__':
main()
我收到:
name_file.txt
1.[[name, surname, city], [name1, surname1, city1], ...]
2.
3.
我找不到让每条记录都换行的方法...像这样:
1. [name, surname, city],
2. [name1, surname1, city1],
3. [name2, surname2, city2],
或更好:
1. name, surame, city
2. name1, surname1, city1
3. name2, surname2, city2
像这样更新您的 save_data
函数。在写入文件之前,您需要从 database
数组格式化生成输出字符串。
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
# generate formatted output
output_str = "\n".join(map(lambda s : ", ".join(s), database))
# write formatted output
data.write(output_str)
data.close()
print(f'Records were create in the file: {name_file}.')
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
for entry in database:
record_string = str(entry[0]) + "," + str(entry[1]) + "," + str(entry[2]) + "\n"
data.write(record_string)
data.close()
print(f'Records were create in the file: {name_file}.')
import random
def main():
print('Program will create a trial database.')
print()
#polish names and surnames
all_names = [name.rstrip() for name in open('names.txt', encoding='utf-8').readlines()]
women_names = [name for name in all_names if name.endswith('a')]
all_surnames = [name.rstrip() for name in open('surname.txt', encoding='utf-8').readlines()]
women_surnames = [sname for sname in all_surnames if not sname.endswith('ski') and not
sname.endswith('cki') and not sname.endswith('sny') and not
sname.endswith('zki')]
men_surnames = [sname for sname in all_surnames if not sname.endswith('ska') and not
sname.endswith('cka') and not sname.endswith('zka') and not
sname.endswith('sna')]
cities = [city.rstrip() for city in open('cities.txt', encoding='utf-8').readlines()]
def record():
"""Function creates records based on file input."""
while True:
try:
num_records = int(input("Enter the number of records: "))
break
except ValueError:
print('Invalid value! Try again...')
database = []
for i in range(1, num_records + 1):
name_choice = random.choice(all_names)
if name_choice in women_names:
sname_choice = random.choice(women_surnames)
else:
sname_choice = random.choice(men_surnames)
city_choice = random.choice(cities)
database.append([name_choice, sname_choice, city_choice])
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
data.write(str(database))
data.close()
print(f'Records were create in the file: {name_file}.')
save_data()
record()
if __name__ == '__main__':
main()
我收到: name_file.txt
1.[[name, surname, city], [name1, surname1, city1], ...]
2.
3.
我找不到让每条记录都换行的方法...像这样:
1. [name, surname, city],
2. [name1, surname1, city1],
3. [name2, surname2, city2],
或更好:
1. name, surame, city
2. name1, surname1, city1
3. name2, surname2, city2
像这样更新您的 save_data
函数。在写入文件之前,您需要从 database
数组格式化生成输出字符串。
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
# generate formatted output
output_str = "\n".join(map(lambda s : ", ".join(s), database))
# write formatted output
data.write(output_str)
data.close()
print(f'Records were create in the file: {name_file}.')
def save_data():
name_file = input('Enter the name of the text file [name.txt]: ')
data = open(name_file, 'w', encoding='utf=8')
for entry in database:
record_string = str(entry[0]) + "," + str(entry[1]) + "," + str(entry[2]) + "\n"
data.write(record_string)
data.close()
print(f'Records were create in the file: {name_file}.')