2014-07-01 56 views
-1

我有一個叫usernames.py文件可能包含列表或沒有在所有存在追加到它:從文件中讀取一個列表,並使用Python

usernames.py

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

在Python我現在想,如果它的存在是爲了讀取這個文件,並追加到列表中的新用戶或創建與該用戶即[「用戶3」]列表

這是我曾嘗試:

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

這給了我一個錯誤未解決的'追加'。我怎樣才能做到這一點? Python不知道它是一個列表,如果該文件不存在甚至最差,因爲我沒有任何東西可以轉換爲列表。

+0

是的,但是因爲它看起來像一個列表,Python不知道,還是我必須告訴python它是一個列表? – Prometheus

+0

你應該使用'r +'模式。否則,在讀取文件之前,文件會被截斷。 – falsetru

+0

@falsetru會根據我的需要創建一個文件,如果文件不存在? – Prometheus

回答

0

試試這個:

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

但這是相當不安全的,如果你不知道文件是因爲它可能包括任何代碼做任何事情!

+1

不知道爲什麼大家都討厭這個答案? –

+0

不知道爲什麼傑米。你似乎已經閱讀我的OP並回答了問題,謝謝。 – Prometheus

0

最好不要使用python文件進行持久化 - 如果有人將你的用戶名滑入你的usernames.py中,會發生什麼情況?考慮一個csv文件或一個pickle,或者一個文本文件,每行只有一個用戶。

這就是說,如果你不打開它作爲一個Python文件,這樣的事情應該工作:

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

如果用戶名包含在引號逗號或結束時,你必須要更加小心。