2017-06-05 38 views
-1

我有一個字符串分配給對方像「太陽 - 月亮」的txt文件,我想獲得指定的值(無論哪一個)的特定字符串if它將來自用戶的輸入,如果沒有的話創建文件一雙新的,並把它寫它:Python 3:搜索文件中的特定字符串

user_input = input() 

if user_input in open('base.txt').read(): 
    print(True) # it's just to be sure that everything really works 
else: 
    base_file = open('base.txt', 'a+') 
    base_file.write(user_input) 
    base_file.write('\n') 
    base_file.close() 
+0

我不確定我的理解。你有一個帶有密鑰對的文件,如字典接受文本,你想搜索「太陽」並返回「月亮」?如果這是正確的,我會考慮使用泡菜。 – 16num

+0

是的,那是對的。我只是不知道該怎麼去實現它。 –

回答

0
import pickle 

myDictA = {'sun': 'moon'} 

with open('myFile.pkl', 'w') as file: 
    pickle.dump(myDict, file) 

with open('myFile.pkl', 'r') as file: 
    myDictB = pickle.load(file) 

print("myDictA:", myDictA) 
print("myDictB:", myDictB) 

你也可以在文件中集成的gzip節省加載過程以節省磁盤空間,如果您想。另一種選擇是使用cPickle,它應該以相同的方式書寫,據說速度可以高達1000倍。

0

對當前代碼的一點補充。

user_input = input() 
flag=1 
with open('base.txt') as f: 
    data=f.read() 
    if user_input in data: 
    print(data) 
    flag=0 
if flag: 
    base_file = open('base.txt', 'a+') 
    base_file.write(user_input) 
    base_file.write('\n') 
    base_file.close()