Search code examples
pythonfopenfwrite

Open function with CSV file on Python


Okay, what I want to do is to write something into a CSV file. I'm doing this:

directory = open('docs/directory.csv', 'a+', encoding='utf-8')
name = input('Please insert a name: ')
phone = input('Please insert a phone number: ')

directory.write(name + ',' + phone + ',\n')

print(directory.read())

I use 'a+' to append every line at the end of the file. Here everything is okay, the data is being added to the end of the file everytime I run the script, but the problem is that the data is not being showed at the end, apparently, the read() function is not working.

Am I doing something wrong? Could you help me with this please? Thanks.


Solution

  • When you call read, you read from the current position of the file pointer to the end of the file. However, you have the file pointer at the end of the file already, so there is nothing returned.

    In this case, I would open the file in 'rw+' mode, seek to the end and then append stuff.

    directory = open('docs/directory.csv', 'a+', encoding='utf-8')
    directory.seek(0,2) #seek to the end
    
    name = input('Please insert a name: ')
    phone = input('Please insert a phone number: ')
    
    directory.write(name + ',' + phone + ',\n')
    
    directory.seek(0) #seek back to beginning
    print(directory.read())