-1

I have a file called usernames.py that may contain a list or does exist at all:

usernames.py

['user1', 'user2', 'user3']

In Python I now want to read this file if it exists and append to the list a new user or create a list with that user i.e. ['user3']

This is what I have tried:

with open(path + 'usernames.py', 'w+') as file:
        file_string = host_file.read()
        file_string.append(instance)
        file.write(file_string)

This gives me an error unresolved 'append'. How can I achieve this? Python does not know it is a list and if the file does not exist even worst as I have nothing to convert to a list.

Prometheus
  • 32,405
  • 54
  • 166
  • 302
  • Yes, but as it 'looks' like a list does Python not know, or do I have to tell python it is a list? – Prometheus Jul 01 '14 at 13:59
  • You should use `r+` mode. Otherwise the file is truncated before you read it. – falsetru Jul 01 '14 at 14:02
  • @falsetru would a+ work as I need it to create the file if it does not exist? – Prometheus Jul 01 '14 at 14:05
  • 1
    @Spike, No. You can't change the file position (`file.seek`) if you open the file with `a` mode. (At least in Linux, write always happend at the end of the file.) – falsetru Jul 01 '14 at 14:07
  • 1
    a+ would work for reading only if you start with `file.seek(0)` (start at beginning) otherwise you are are the end of the file already. – Shadow9043 Jul 01 '14 at 14:08
  • @falsetru so does 'r+' also allow creating of the file it one does not exist? – Prometheus Jul 01 '14 at 14:08
  • Whenever you read from a file, using filehandle.read() in python it will always return you a string. – kvivek Jul 01 '14 at 14:08
  • With respect to the open mode I would suggest to go through this [link] (http://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r) – kvivek Jul 01 '14 at 14:11
  • Are you fixed on the file type? You could use [pickle](https://docs.python.org/3.3/library/pickle.html?highlight=pickle#module-pickle) or [json](https://docs.python.org/3.3/library/json.html?highlight=json#module-json) to be able to read and write python objects to files – Shadow9043 Jul 01 '14 at 14:14

2 Answers2

0

Try this:

import os

filename = 'data'
if os.path.isfile(filename):
    with open(filename, 'r') as f:
        l = eval(f.readline())
else:
    l = []

l.append(instance)
with open(filename, 'w') as f:
    f.write(str(l))

BUT this is quite unsafe if you don't know where the file is from as it could include any code to do anything!

Jamie Cockburn
  • 7,379
  • 1
  • 24
  • 37
0

It would be better not to use a python file for persistence -- what happens if someone slips you a usernames.py that has exploit code in it? Consider a csv file or a pickle, or just a text file with one user per line.

That said, if you don't open it as a python file, something like this should work:

from os.path import join
with open( join(path, 'usernames.py'), 'r+') as file:
    file_string = file.read()
    file_string = file_string.strip().strip('[').strip(']')
    file_data = [ name.strip().strip('"').strip("'") for name in file_string.split(',' )]
    file_data.append( instance )
    file.fseek(0)
    file.write(str(file_data))

If usernames contain commas or end in quotes, you have to be more careful.

shaunc
  • 5,317
  • 4
  • 43
  • 58