2016-06-30 133 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)