Python 这个读/写文件脚本有什么问题?
此脚本用于搜索文件、读取文件并替换指定的引用。例如,在CMD中,我应该能够输入python modify.py smbd.txt“password sync=yes”“password sync=no” 通过在CMD中输入此项,脚本应将smbd.txt文件中出现的所有“password sync=yes”替换为“password sync=no” 然而,我很难做到这一点,因为我在运行代码时会出错。我们没有在课堂上学习这个,我不知道我应该如何知道如何正确地编写脚本。我只是觉得我遗漏了一些东西,可能与读取txt文件中的行有关?这就是我目前所拥有的。任何帮助都将不胜感激 错误Python 这个读/写文件脚本有什么问题?,python,writetofile,writing,Python,Writetofile,Writing,此脚本用于搜索文件、读取文件并替换指定的引用。例如,在CMD中,我应该能够输入python modify.py smbd.txt“password sync=yes”“password sync=no” 通过在CMD中输入此项,脚本应将smbd.txt文件中出现的所有“password sync=yes”替换为“password sync=no” 然而,我很难做到这一点,因为我在运行代码时会出错。我们没有在课堂上学习这个,我不知道我应该如何知道如何正确地编写脚本。我只是觉得我遗漏了一些东西,可能
问题在于
outFile
和fileSpec
只是一个字符串,您试图对它们进行写入或读取。您需要使用outPointer
和inPointer
,文件句柄可能是为此而创建的。并且优选地在上下文管理器内,例如:
with open(outFile, 'w') as outPointer:
with open(fileSpec, 'r') as inPointer:
for line in inPointer
outPointer.write(line.replace(searchText, replaceText))
outPointer.write('\n') # If you want each line from the input
# to be on its own line in the output
使用带有open(…)上下文管理器的,您无需担心调用.close()
,这是为您完成的。大多数情况下,您只需要将字符串和文件清楚地分开,并将它们用于预期目的
希望对你有帮助,编码快乐 你犯了什么错误?请编辑此帖子以包含类似的详细信息。由于下面的建议,更新了我添加的错误,readlines()
。删除它后,只需对inPointer:
中的行使用,脚本现在就通过了我的所有测试。刚刚将所有出现的“password sync=yes”更改为“password sync=no”@Chase您对问题所做的编辑有点使答案不相关,因为它似乎已经是您正在做的事情了。请不要编辑问题修正或答案以保持文章的相关性。你可以把它作为一个单独的编辑发布,在评论中谈论它,或者问一个新问题。我恢复了你的编辑,使山姆的答案相关。如果它最终帮助了你,请随意投票,如果它解决了你的问题,请接受它。我理解,对此感到抱歉!我更改了脚本中的一些内容,并更新了OP上的编辑。仍然无法使其工作。我现在做错什么了?谢谢你,托梅里库。我删除了,readlines()
,脚本现在运行良好。谢谢Sam解释我用错了指针。抱歉,,readlines
是一个打字错误,eeps@Tomerikoo OP没有阅读指针,帖子后来更新了。对不起,Sam,没有注意到帖子被更改:)很高兴它能工作,如果我的答案有帮助,请随意投票并接受它为正确!星期五快乐!
import sys
#get the command line arguments
if len(sys.argv) != 4:
print("usage: modify.py fileSpec from to")
exit(1)
fileSpec = sys.argv[1]; # read file name first arg
searchText = sys.argv[2]; # text to search for
replaceText = sys.argv[3]; # text to replace with
outFile = fileSpec + '.new' # write file = read file with .new append
outPointer = open(outFile, 'w') # open write file
inPointer = open(fileSpec, 'r') # open read file
for line in fileSpec:
#foreach line replace the strings
outFile.write(line.replace(searchText, replaceText))
fileSpec.close()
outFile.close()
with open(outFile, 'w') as outPointer:
with open(fileSpec, 'r') as inPointer:
for line in inPointer
outPointer.write(line.replace(searchText, replaceText))
outPointer.write('\n') # If you want each line from the input
# to be on its own line in the output