0

我有一个脚本可以在将文件上传到 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'
4

1 回答 1

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'

区别在于:

  • 使用 with 语句确保文件无论成功还是引发异常都关闭
  • open()调用结果分配给名称 ( f)
  • 添加缺少的括号,ftp.close()以便调用该函数。
于 2012-07-30T16:04:37.097 回答