我正在尝试在python中创建一个程序来编辑当前目录中的文件,并在程序结束时添加代码。我还没有完成它,但我已将病毒的标记放在我的其他文件中并启动程序以查看标记是否在其他代码中并且它总是返回false。不确定为什么会这样做。
import os
path = ("/python34")
def infected(__file__):
if("#@! infected by virus ;) !@#") in (__file__):
print("True.")
else:
print("False.")
def selectTarget():
os.getcwd()
os.listdir(path)
def copyCode(__file__):
open(__file__, 'r+')
victimfile=open(__file__)
selectTarget()
infected(__file__)
copyCode(__file__)
答案 0 :(得分:0)
这不会引发错误的唯一原因是您已选择内置变量(__file__
)作为函数的参数。你不应该使用内置名称有很多原因,但问题在于它掩盖了真正的错误。
因此,将__file__
更改为filename
,您就会开始遇到很多错误。例如,它从未定义过。在你定义它之后,你会发现你的函数没有返回任何东西,所以一旦它们退出就会丢弃它们。
我认为你应该在执行这个更复杂的任务之前完成python教程!你会为自己省去很多困惑。
答案 1 :(得分:0)
这可能有用。我接受了“tdelaney”的建议并编辑了你的原始代码。希望这有帮助,如果有人编辑以使其更好,请做。
import os
filename = raw_input("File Name: ") # Type whatever your file is
path = ("/python34")
def infected(filename):
if("#@! infected by virus ;) !@#") in (filename):
return True
else:
return False
def selectTarget():
os.getcwd()
path_list = os.listdir(path)
return path_list
def copyCode(filename):
open(filename, 'r+')
victimfile=open(filename)
return victimfile
for i in selectTarget():
if infected(filename) == True:
infected_file = copyCode(filename)
# Do something with infected file