这个读/写文件脚本在做什么?

问题描述 投票:0回答:1

该脚本应搜索文件,读取文件并替换指定的出现位置。例如,在CMD中,我应该能够输入python Modify.py smbd.txt“密码同步=是”“密码同步=否”

通过在CMD中输入此内容,脚本应将smbd.txt文件中所有出现的“ password sync = yes”替换为“ password sync = no”

但是,由于在运行代码时遇到错误,因此我很难做到这一点。我们在课堂上没有学过,我也不知道该如何正确编写脚本。我只是觉得我缺少什么,可能与读取txt文件中的行有关?到目前为止,这就是我所拥有的。任何帮助,将不胜感激。

错误

Traceback (most recent call last):

File "modify.py", line 18, in <module>
    outFile.write(line.replace(searchText, replaceText))
AttributeError: 'str' object has no attribute 'write'
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()
python writetofile writing
1个回答
0
投票

问题是outFilefileSpec只是一个字符串,您尝试对其进行写入或读取。您需要使用outPointerinPointer,大概是为此目的而制作的文件句柄。最好在上下文管理器中,例如:

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

使用with open(...)上下文管理器,您无需担心调用.close(),它已为您完成。通常,您只需要将字符串和文件处理区明确分开,并将其用于预期的目的即可。

希望有帮助,编码愉快!

© www.soinside.com 2019 - 2024. All rights reserved.