我有以下代码: 我需要通过在开头放置 # 来删除一行。它很好用。 问题是如果该行已经被# 注释掉,并且再次运行查询。它在行中放置第二个#。在实际文件“getweather.sh”中,我得到了一行看起来像的行。如何搜索准确的文本?
####home/pi/allsky/get-temp.py
# Read in the file
with open('/home/pi/allsky/getweather.sh', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('/home/pi/allsky/get-temp.py', '#/home/pi/allsky/get-temp.py')
# Write the file out again
with open('/home/pi/allsky/getweather.sh', 'w') as file:
file.write(filedata)
我认为将整个文件作为单个字符串读取是错误的方法;您可以通过调用
readlines()
以字符串数组的形式读取文件(每行文本一个字符串)并逐行处理它来更轻松地获得您想要的行为,如下所示:
filePath = '/home/pi/allsky/getweather.sh'
# Read all lines of the file into an array of strings
with open(filePath, 'r') as inFile :
inputLines = inFile.readlines()
# Write the array of strings back to the file, with # modification
with open(filePath, 'w') as outFile:
for line in inputLines:
line = line.strip() # remove carriage-return/newline from the end
if (line == '/home/pi/allski/get-temp.py'):
outFile.write('#')
outFile.write(line)
outFile.write('\n')