Python 无法写入文件
我试图让字符串写入文本文件,但前提是该字符串不在文本文件中Python 无法写入文件,python,file,Python,File,我试图让字符串写入文本文件,但前提是该字符串不在文本文件中 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+') outp
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)
上面的代码在文件夹中创建新文件,但其中没有任何内容。
有什么建议吗?for循环中的逻辑错误。它不是检查文件中是否缺少字符串,而是检查文件中是否有与字符串不匹配的行。如果文件为空,则循环不会执行任何操作,因此它不会将found设置为=1
你需要颠倒逻辑。将其更改为:
found = False
for line in lines:
if line == c:
found = True
break
if not found:
output_filee.write(c)
我注意到你的片段中有几点 首先,您使用的是操作系统模块,但它没有导入 第二,你想让它只在windows上工作吗?因为os.system调用充其量只是“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))
您可以将读/写合并到单个循环中。我通常会做一些其他的事情来整理这篇文章,但我只有几分钟的时间来发布这篇文章。希望这能为您指明写入方向。您可以使用如下函数:
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)
除了中提到的有缺陷的逻辑之外,还有一些问题: 在当前设置下,新文件将只包含新的播放器名称,而我认为您希望新文件也包含所有以前的名称。 ifline!=c将始终为false,因为行的末尾将始终有一个\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)
找到的变量之前已定义。循环中的逻辑错误。如果有与c不同的行,即使c与其他行匹配,它也会将find=1。代码中有很多逻辑错误。