我有一个脚本在将文件上传到FTP之前重命名文件。首先,它搜索模式“_768x432_1700_m30_”,如果它发现模式被“ new ”替换 - 然后它将目录中的所有“.mp4”文件上传到FTP服务器。但由于某种原因,我似乎无法删除上传后的文件?还有更好的方法来执行此脚本吗? (我对python很新)
#!/usr/bin/python
import os
import glob
import fnmatch
import sys
import ftplib
import shutil
import re
from ftplib import FTP
Host='xxxxxx.xxxxx.xxxx.com'
User='xxxxxxx'
Passwd='xxxxxxx'
ftp = ftplib.FTP(Host,User,Passwd) # Connect
dest_dir = '/8619/_!/xxxx/xx/xxxxx/xxxxxx/xxxx/'
Origin_dir = '/8619/_!/xxxx/xx/xxxxx/xxxxxx/xxxx/'
pattern = '*.mp4'
file_list = os.listdir(Origin_dir)
for filename in glob.glob(os.path.join(Origin_dir, "*_768x432_1700_m30_*")):
os.rename(filename, filename.replace('_768x432_1700_m30_','_new_' ))
video_list = fnmatch.filter(filename, pattern)
print(video_list)
print "Checking %s for files" % Origin_dir
for files in file_list:
if fnmatch.fnmatch(files, pattern):
print(files)
print "logging into %s FTP" % Host
ftp = FTP(Host)
ftp.login(User, Passwd)
ftp.cwd(dest_dir)
print "uploading files to %s" % Host
ftp.storbinary('STOR ' + dest_dir+files, open(Origin_dir+files, "rb"), 1024)
ftp.close
print 'FTP connection has been closed'
答案 0 :(得分:1)
在以下行中
ftp.storbinary('STOR ' + dest_dir+files, open(Origin_dir+files, "rb"), 1024)
你打开一个文件,但你没有保留对它的引用并关闭它。在Windows上(我假设你在Windows上运行它),当进程打开文件时,无法删除文件。
请尝试以下方法:
print "uploading files to %s" % Host
with open(Origin_dir+files, "rb") as f:
ftp.storbinary('STOR ' + dest_dir+files, f, 1024)
ftp.close()
print 'FTP connection has been closed'
区别在于:
open()
来电的结果分配给名称(f
)ftp.close()
添加了缺少的括号,以便调用该函数。