在 python 中使用 os.utime 更改后文件修改时间恢复

JAC*_*JAC 1 python filemtime

我在 python 2.7.1(在 Mac OS X 10.7.5 上运行)中使用 os.utime 命令遇到了问题

我正在尝试开发一个脚本,从 FTP 下载符合某些条件的文件,但如果该文件存在并且我已经在本地目录上有它的副本,那么我想检查文件修改时间。如果它们不匹配,我就会下载新副本。为了实现这个目标,我获取 FTP 文件修改时间,将其转换为时间戳,然后使用 os.utime 更改下载文件的访问和修改日期,以匹配 FTP 服务器的访问和修改日期。我的问题是,一旦我从更改访问和修改时间的子例程中退出,它们就会恢复为原始时间!我没有在后台运行任何东西,我还在 Linux 服务器上测试了脚本,结果相同

如果您运行下面的代码两次,它将在调试注释中显示问题,因为 FTP 服务器中的文件没有更改,但时间戳与正确更改的本地文件不匹配。预先感谢您对此问题的任何帮助。

import ftplib
import os
from datetime import datetime

def DownloadAndSetTimestamp(local_file,fi,nt):
    lf=open(local_file,'wb')
    f.retrbinary("RETR " + fi, lf.write, 8*1024)
    lf.close
    print fi + " downloaded!"

    print "-> mtime before change : " + str(os.stat(local_file).st_mtime)   
    print "-> atime before change : " + str(os.stat(local_file).st_atime)   
    print "-> FTP value     : " + str(int(nt))
    #set the modification time the same as server for future comparison
    os.utime(local_file,( int(nt) , int(nt) ))
    print "-> mtime after change  : "+ str(os.stat(local_file).st_mtime)
    print "-> atime after change  : "+ str(os.stat(local_file).st_atime)

print "Connecting to ftp.ncbi.nih.gov..."   
f=ftplib.FTP('ftp.ncbi.nih.gov')
f.login()
f.cwd('/genomes/Bacteria/')
listing=[]
dirs=f.nlst();
print "Connected and Dir list retrieved."

target_bug="Streptococcus_pseudopneumoniae"
print "Searching for :"+ target_bug
ct=0;
Target_dir="test/"
for item in dirs:
    if item.find(target_bug)>-1:
        print item
        #create the dir
        if not os.path.isdir(os.path.join(Target_dir,item)):
            print "Dir not found. Creating it..."
            os.makedirs(os.path.join(Target_dir,item))
        #Get the gbk 
        #1) change the dir
        f.cwd(item)
        #2) get *.gbk files in dir
        files=f.nlst('*.gbk')
        for fi in files:
            print "----------------------------------------------"
            local_file = os.path.join(Target_dir,item,fi)
            if os.path.isfile(local_file):
                print "################"
                print "File " + local_file + " already exists."
                #get remote modification time           
                mt = f.sendcmd('MDTM '+ fi)
                #converting to timestamp
                nt = datetime.strptime(mt[4:], "%Y%m%d%H%M%S").strftime("%s")
                #print "mtime FTP :" + str(int(mt[4:]))
                #print "FTP M timestamp   : " + str(nt)
                #print "Local M timestamp : " + str(os.stat(local_file).st_mtime)
                #print "Local A timestamp : " + str(os.stat(local_file).st_atime)

                if int(nt)==int(os.stat(local_file).st_mtime):
                    print fi +" not modified. Download skipped"
                else:
                    print "New version of "+fi
                    ct+=1
                    DownloadAndSetTimestamp(local_file,fi,nt)
                    print "NV Local M timestamp : " + str(os.stat(local_file).st_mtime)
                    print "NV Local A timestamp : " + str(os.stat(local_file).st_atime)
                print "################"

            else:
                print "################"
                print "New file: "+fi
                ct+=1
                mt = f.sendcmd('MDTM '+ fi)
                #converting to timestamp
                nt = datetime.strptime(mt[4:], "%Y%m%d%H%M%S").strftime("%s")
                DownloadAndSetTimestamp(local_file,fi,nt)
                print "################"

        f.cwd('..')
f.quit()
print "# of "+target_bug+" new files found and downloaded: " + str(ct)
Run Code Online (Sandbox Code Playgroud)

use*_*342 5

lf.close您缺少;中的括号 它应该是lf.close()

如果没有括号,您实际上就没有关闭文件。相反,在您调用 后,垃圾收集器会稍后关闭该文件os.utime。由于关闭文件会刷新未完成的 IO 缓冲区内容,因此修改时间将作为副作用而更新,从而破坏您之前设置的值。