im试图通过在config.dat文件中读取使用shutil复制文件。
该文件简单:/home/admin/documents/file1/home/admin/documents/file2
代码确实有效,但是它将复制file1好的,但是错过了file2,因为它在那里看到一个 n,我猜是因为新行是因为新行。
#!/usr/bin/python3
import shutil
data = open("config.dat")
filelist = data.read()
src = filelist
dest = '/home/admin/Documents/backup/'
shutil.copy(src, dest)
错误代码im获取:
Traceback (most recent call last):
File "./testing.py", line 18, in <module>
shutil.copy(src, dest)
File "/usr/lib/python3.4/shutil.py", line 229, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.4/shutil.py", line 108, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory:
'/home/admin/Documents/file1n/home/admin/Documents/file2'
我希望这些文件的副本根据config.dat文件夹的文件运行,但它检测到'n'
。有办法解决此问题吗?
感谢您的帮助
使用 split('n')
获取文件列表和迭代列表。您可能想投入file.strip()
以摆脱尾随的空间和空线。
import shutil
dest = '/home/admin/Documents/backup/'
with open('config.dat') as data:
filelist = data.read().split('n')
for file in filelist:
if file:
shutil.copy(file.strip(), dest)
或,如果您在此之后不需要filelist
with open('config.dat') as data:
for file in data:
if file:
shutil.copy(file.strip(), dest)