简体   繁体   中英

Need help placing info on a new line in a file

im trying to create a database by using dictionaries. i convert the dictionary into a string once ive finished adding and deleting things from it but when i want to save the string, i would like the the keys to be on a new line from each other.

here is my code so far:

print('|-----Welcome to the Address Book-------|')
print('|----------------------------------------|')
print('|Please choice from the following:-------|')
print('|----------1: Find   Contact------------|')
print('|----------2: Add    Contact------------|')
print('|----------3: Delete Contact------------|')
print('|----------4: Quit Address Book----------|')

choice = [1, 2, 3, 4, 5]


document = open('addresses.txt', 'r+')
address = {}
for line in document:
    if line.strip():
        key, value = line.split(None, 1)
        address[key] = value.split()
document.close()
open('addresses.txt', 'w')

while 1:
    answer = 0
    while answer not in choice:
        try:
            answer = int(input("Enter here: "))
        except ValueError:
            0

    if answer == 1:
        x = input('Enter his/her name: ')
        if x in address:
            print("This is their address: ", address[x])
        else:
            print('Contact does not exist!')

    if answer == 2:
        x = (input('Enter new contact: '))
        x = x.replace(" ", "_")
        if x in address:
            while True:
                z = str(input('Contact '+x+' with address: '+str(address[x]) + ' already existed, do you want to override?(Yes/No)'))
                if z == 'yes':
                    b = input('Enter Address: ')
                    c = input('Enter postcode: ')
                    del address[x]
                    break

                elif z == 'no':
                    break
                else:
                    print('Please choose yes or no')

        else:
            b = input('Enter Address: ')
            c = input('Enter postcode: ')
        b = b.replace(" ", "_")
        c = c.replace(" ", "_")
        address[x] = b, c

    if answer == 3:
        z = input('Enter whom you would like to delete: ')
        if z in address:
            del address[z]
        else:
            print('Contact does not exist!')

    if answer == 4:
        a = "{}':(),[]"
        ok = str(address)

        for char in a:
            ok = ok.replace(char, "")

        document = open('addresses.txt', 'r+')
        document.write(ok + '\n')
        document.close()
        break

when saving to file, i would like to save each key and its info like this:

>Bob address postcode
>Sam address postcode

but instead it is saved like this:

>Bob address postcode Sam address postcode

When writing a dictionary to file, do the following:

with open('/file/path', 'w') as f:
    for k, v in d.items():
        f.write(k + v + "\n")

This assumes a few things:

  1. You want to overwrite the file, not append; if you do, switch 'w' to 'a'
  2. All the key and value items are str

I don't like using 'r+' . You should open(filename, "r") when you want to read from a file and open(filename, "w") when you want to read your file. In my opinion, it's way easier because while using 'r+' , you have to think about where the seek is (the blinking cursor that you see while writing/editing somewhere). For that you'll need something like:

file=open(filename,"r+")
file.seek(0)
file.write("something" + "\n")

Well, I don't really use the "r+" method very much so I can't explain anymore. I suggest that you read more about it in the docs.

If you print str(address) to your screen, you will understand why this happens. The str command converts everything (ie keys and values) to a concatanated string and that will be stored in your document file.

Instead you should save the items of your address book one by one, iterating over all persons.

ok = ""
for person in address:
    ok += person + " " + address[person] + "\n"

with open('addresses.txt', 'w') as file_out:
    file_out.write(ok)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM