我正在研究一个问题,即创建一个程序来获取文件的用户输入,然后在文件中删除用户指定的字符串.我不确定如何从我所拥有的(下面)到问题所要求的内容.一如既往,非常感谢任何和所有的帮助.
def main():
outfile = open(input("Enter a file name: "), "a")
string = input("Enter the string to be removed: ")
for string in outfile.readlines():
string = string.replace(string, "")
outfile.close()
print("Done")
main()
Run Code Online (Sandbox Code Playgroud)
我采取了其中一个建议,并尝试让它工作,但正如我在下面的评论中所说,下面的代码不会返回错误,它会创建一个空文件.我错过了将新文件作为删除字符串的旧文件而丢失的内容?
def main():
inpath = input("Enter an input file: ")
line = input("Enter what you want to remove: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open(outpath, "w") as outfile:
for line in infile:
outfile.write(line.replace(line, "") + "\n")
print("Done.")
main()
Run Code Online (Sandbox Code Playgroud)
在进入细节之前的一些注意事项:当你打电话时string.replace(string, ""),你告诉字符串用空字符串替换它的整个自我 - 你也可以这样做string = "".据推测,第一个string是要替换的搜索字符串,因此请给它一个不同的名称,然后将其用作例如string.replace(searchString, "").此外,您不希望命名变量string,因为它是标准库模块的名称.你正在调用输入文件"outfile",这很容易让人困惑.您可能希望使用with语句而不是显式关闭.最后,你可以只用文件迭代文件中的行for line in f:; 你不需要for line in f.readlines()(而且,如果你需要处理Python 2.x,你会更乐意避免readlines(),因为它会将整个文件读入内存,然后在内存中创建一个巨大的行列表).
JBernardo指出,第一个问题是你以"a"模式打开文件,这意味着"只写,附加到最后".如果要读写,可以使用"a +"或"r +".
但是,这对你没有多大帮助.毕竟,你不能在阅读它的过程中写入文件.
有几种常见的方法可以解决这个问题.
首先,只需写入标准输出,让用户对结果做任何他想做的事情 - 例如,将其重定向到文件.(在这种情况下,你打印你的提示,"完成"消息等,而不是标准错误,所以他们不会被重定向到文件.)这是许多Unix工具喜欢sed或sort做的,所以它是适当的,如果你正在构建一个Unix风格的工具,但可能不适合其他目的.
def stderrinput(prompt):
sys.stderr.write(prompt)
sys.stderr.flush()
return input()
def main():
with open(stderrinput("Enter a file name: "), "r") as infile:
searchString = stderrinput("Enter the string to be removed: ")
for line in infile:
print(infile.replace(searchString, ""))
sys.stderr.write("Done\n")
Run Code Online (Sandbox Code Playgroud)
其次,写入另一个文件.以"r"模式打开输入文件,输出文件以"w",模式,然后你只是复制行:
def main():
inpath = input("Enter an input file: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open("outpath", "w") as outfile:
for line in infile:
outfile.write(line.replace(searchString, "") + "\n")
Run Code Online (Sandbox Code Playgroud)
第三,在内存中读取并处理整个文件,然后截断并重写整个文件:
def main():
path = input("Enter an input/output file: ")
with open(path, "r+") as inoutfile:
lines = [line.replace(searchString, "") for line in inoutfile]
inoutfile.seek(0)
inoutfile.truncate()
inoutfile.writelines(lines)
Run Code Online (Sandbox Code Playgroud)
最后,写入临时文件(与第二个选项一样),然后将该临时文件移动到原始输入文件的顶部.像这样的东西:
def main():
path = input("Enter an input/output file: ")
with open(path, "r") as infile, tempfile.NamedTemporaryFile("w", delete=False) as outfile:
for line in infile:
outfile.write(line.replace(searchString, ""))
shutil.move(outfile.name, pathname)
Run Code Online (Sandbox Code Playgroud)
由于POSIX和Windows之间的差异,最后一个有点棘手.但是,它有一些很大的优点.(例如,如果您的程序在操作过程中被杀死,无论它如何发生,您都可以保证拥有原始文件或新文件,而不是一些半文字.)