2016-06-30 127 views
-3

我想在字符串中寫入一個文本文件,但只有當該字符串已經不在文本文件中。無法寫入文件

b = raw_input("IP Adress: ") 
os.system('cls') 
if(b == '0'): 
    a = 0 
c = raw_input("Player Name: ") 
if(c == '0'): 
    a = 0 
if(a != 0): 
    line = "Text\IPs\{}.txt".format(b) 
    output_filee = open(line, 'w+') 
    output_file = open(line, 'r') 
    lines = output_file.readlines() 
    for line in lines: 
     if(line != c): 
      found = 1 
    if(found == 1): 
     output_filee.write(c) 
    output_file.close() 
    output_filee.close() 
    print '"{}" has been added to the IP Address {}'.format(c,b) 

上面的代碼使新文件在文件夾中,但沒有任何內容。 有什麼建議嗎?

+1

的「發現」變量已經前手定義。 –

+1

循環中的邏輯錯誤。如果有任何與「c」不同的行,即使「c」與其他行相匹配,它也會設置「found = 1」。 – Barmar

+1

代碼中有很多邏輯錯誤。 –

回答

1

for循環中的邏輯錯誤。它不檢查文件中是否缺少字符串,它檢查文件中是否有某行與該字符串不匹配。如果文件爲空,循環將不會執行任何操作,因此它永遠不會設置found = 1

您需要反轉邏輯。更改爲:

found = False 
for line in lines: 
    if line == c: 
     found = True 
     break 
if not found: 
    output_filee.write(c) 
0

有幾件事我已經注意到您的代碼段。

首先,您正在使用os模塊,但未導入。

其次,你想這隻能在Windows上工作嗎?因爲系統調用充其量只是'meh',直到你想跨平臺,然後他們幾乎是毫無價值的。所以,如果這不是問題,那就忽略那個部分。

a在哪裏定義?只有在某些條件不符合的情況下才能定義它。我的建議是爲了避免錯誤,就是設置一些任意的初始狀態,這將防止發生未定義的錯誤。

此外,您的代碼段很難遵循語法。當你寫更多的代碼,或回到舊的代碼,這使得維護非常困難。

考慮這樣的事情以供參考:

import os 
a = "" 
b = raw_input("IP Adress: ") 
found = False 

os.system('cls') 

if(b == '0'): 
    a = 0 

c = raw_input("Player Name: ") 

if(c == '0'): 
    a = 0 

if(a != 0): 
    try: 
     f = "Text/IPs/{}.txt".format(b) 
     with open(f, "w+") as myfile: 
      for line in myfile.read(): 
       if(line == c): 
        found = True 

      if found == False: 
       myfile.write(c) 
       print '"{}" has been added to the IP Address {}'.format(c,b) 

    except Exception, e: 
     print(str(e)) 

您可以鞏固你的讀/寫爲一個循環。還有一些其他的東西,我通常會這樣做,但我只有幾分鐘的時間來發布這個。希望這能讓你指出寫作方向。

0

你可以使用一個函數像這樣的:

def add(filename, text): 
    text += '\n' 
    with open(filename, 'a+') as lines: 
    if not any(text==l for l in lines): 
     lines.write(text) 

ip_adress = raw_input("IP Adress: ") 
name = raw_input("Player Name: ") 
if ip_adress != '0' and name != '0': 
    add(r"Text\IPs\{}.txt".format(ip_adress), name) 
1

除了在Barmar's answer提到的有缺陷的邏輯,有幾個問題:

  • 在當前設置下,新的文件將只包含新玩家的名字,而我認爲你想要的是新文件也包含所有以前的名字。
  • if(line != c)將永遠是false,因爲line最後總會有一個\n

所以,我想你想要這樣的:

import os 


b = raw_input("IP Adress: ") 
a = 1 

if(b == '0'): 
    a = 0 
c = raw_input("Player Name: ") 
if(c == '0'): 
    a = 0 

if(a != 0): 
    filepath = "{}.txt".format(b) 

    found = False 
    if os.path.exists(filepath): 
     output_file = open(filepath, 'r') 
     lines = output_file.readlines() 
     output_file.close() 
     for line in lines: 
      if line.rstrip() == c: 
       found = True 
       print '"{}" already present\n'.format(c) 
       break 

    if not found: 
     output_filee = open(filepath, 'a') 
     output_filee.write(c + '\n') 
     output_filee.close() 
     print '"{}" has been added to the IP Address {}'.format(c, b)