Skip to content
Advertisement

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() 

I receivng: name_file.txt

1.[[name, surname, city], [name1, surname1, city1], ...]
2.
3.

I can’t find a way to get every record on a new line… like this:

1. [name, surname, city],
2. [name1, surname1, city1],
3. [name2, surname2, city2],

or better:

1. name, surame, city
2. name1, surname1, city1
3. name2, surname2, city2

Advertisement

Answer

Update your save_data function like this. You need to format generate output string from database array before writing into file.

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}.')
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement