目录中文件的Python附加器

2024-05-28 23:55:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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__)

Tags: 文件path代码标记程序编辑osdef
2条回答

这不会引发错误的唯一原因是您选择了一个内置变量(__file__)作为函数的参数。出于许多原因,您不应该使用内置名称,但这里的问题是它掩盖了真正的bug。在

所以,将__file__改为filename,你会发现很多错误。例如,它从未定义过。在你定义它之后,你会发现你的函数不返回任何东西,所以一旦它们退出,它们计算的任何东西都会被丢弃。在

我认为在开始这个更复杂的任务之前,您应该先阅读python教程!你会省去很多困惑。在

这可能有用。我接受了“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

相关问题 更多 >

    热门问题