2017-06-05 50 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()