不带文件名保存当前Python文件内容

不带文件名保存当前Python文件内容,python,filenames,Python,Filenames,因此,我需要能够跨当前文件内容(前20个字符)复制到另一个文件,而无需使用文件名,因为这可以在任何时候更改。我该怎么办?到目前为止,我有此代码,但它使用了文件名: h="this a a virus!" i="This will not be copied" print("You Have Successfully Copied into your target file!") infile = open ("assignment1.py", 'r') filestr = infile.rea

因此,我需要能够跨当前文件内容(前20个字符)复制到另一个文件,而无需使用文件名,因为这可以在任何时候更改。我该怎么办?到目前为止,我有此代码,但它使用了文件名:

h="this a a virus!"
i="This will not be copied"
print("You Have Successfully Copied into your target file!")

infile = open ("assignment1.py", 'r')
filestr = infile.read()
appendFile = filestr[0:20]


L = list()
f = open('target.py', 'r')
for line in f.readlines():
    L.append(line)
L.insert(0,appendFile)
f.close()

fi = open('target.py', 'w')
for line in range(len(L)):
    fi.write(L[line])

fi.close()
您可以将文件夹与文件一起使用:

from os import listdir

files = listdir('path_to_folder')

for one_file in file:
    with open(one_file, 'r') as f:
        data = f.read(20)
    with open(one_file, 'w') as f:
        full_data = f.read() + data
        f.write(full_data)

是否要写入一个没有名称的文件?它是我要复制的当前文件。这只是该文件的前20个字符(据推测病毒是如何工作的),但由于文件名可能会更改,我无法使用open(filename)方法调用它。您的意思是
sys.argv[0]
?旁注:
表示f中的行。readlines():
几乎总是最好表示为
表示f中的行:
;前者在迭代之前将整个文件拖入一个不必要的
列表
,后者在读取时进行迭代。当然,所有这些代码通常都是反Pythonic的(
for i in range(len(L)):
应该是
for line in L:
直接迭代行,而不是迭代索引和索引)。等等,您想将一个文件的前20个字符复制到另一个文件,而不改变什么。请多解释