所以我需要能够在不使用文件名的情况下将当前文件内容(前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()
答案 0 :(得分:0)
您可以将listdir用于包含文件的文件夹:
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)