【问题标题】:Creating year / month / day folder structure with Python in FTP在 FTP 中使用 Python 创建年/月/日文件夹结构
【发布时间】:2018-10-25 12:32:05
【问题描述】:

我正在寻找使用 Python ftplib 模块创建年/月/日文件夹结构的选项

连接:

ftp = ftplib.FTP(ftp_servidor, ftp_usuario, ftp_clave)

加载变量:

ftp_raiz = 'TEST/'
filename = '2019-10-01T00-00-00.txt'

功能:

def cdTree(ftp, filename=None, path=None):

    if filename is not None:
        date = datetime.datetime.strptime(filename, '%Y-%m-%dT%H-%M-%S.txt')
        path = ftp_raiz + date.strftime('%Y') + '/' + date.strftime('%m') + '/' + date.strftime('%d')
        print filename
    if path != "":
        try:
            ftp.cwd(path)
        except error_perm as e:
            print e, ", creating folder"
            print path
            cdTree(ftp, path="/".join(path.split("/")[:-1]))
            ftp.mkd(path)
            ftp.cwd(path)

cdTree(ftp, filename, 'TEST')

最后我没有创建文件夹结构,它抛出了以下错误:

2018-10-18T00-00-00.txt
550 Failed to change directory. , creating folder
2018/10/18
550 Failed to change directory. , creating folder
2018/10
Traceback (most recent call last):
  File "ftp2.py", line 34, in <module>
    cdTree(ftp, filename)
  File "ftp2.py", line 30, in cdTree
    cdTree(ftp, path="/".join(path.split("/")[:-1]) )
  File "ftp2.py", line 31, in cdTree
    ftp.mkd(path)
  File "C:\python27\lib\ftplib.py", line 589, in mkd
    resp = self.sendcmd('MKD ' + dirname)
  File "C:\python27\lib\ftplib.py", line 251, in sendcmd
    return self.getresp()
  File "C:\python27\lib\ftplib.py", line 226, in getresp
    raise error_perm, resp
ftplib.error_perm: 550 Create directory operation failed.

注意:只做一个文件夹的测试就可以了!

【问题讨论】:

    标签: python linux ftp ftplib


    【解决方案1】:

    你的代码对我来说没有多大意义。

    我相信你想要这个:

    def cdTree(ftp, path):
        print "entering folder {0}".format(path)
        try:
            ftp.cwd(path)
        except:
            print "failed to enter, creating"
            cdTree(ftp, path="/".join(path.split("/")[:-1]))
            ftp.mkd(path)
            ftp.cwd(path)
    
    ftp_raiz = 'TEST/'
    filename = '2019-10-01T00-00-00.txt'
    
    date = datetime.datetime.strptime(filename, '%Y-%m-%dT%H-%M-%S.txt')
    path = ftp_raiz + date.strftime('%Y/%m/%d')
    
    cdTree(ftp, path)
    

    【讨论】:

    • 思路是根据日期生成文件夹结构,你的代码可以正常工作,谢谢!
    【解决方案2】:

    我不确定这是否有帮助,但在 HDFS 文件系统上尝试了同样的方法,它帮助我解决了我的要求。可以在函数 generateDateFromThisYear() 中更改所需的输出

    import datetime as d
    import subprocess
    
    def run_cmd(args_list):
        """
        run linux commands
        """
        # import subprocess
        print('Running system command: {0}'.format(' '.join(args_list)))
        proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        s_output, s_err = proc.communicate()
        s_return = proc.returncode
        return s_return, s_output, s_err
    
    def hdfsMakedir(hdfs_file_path):
        (ret, out, err) = run_cmd(['hdfs', 'dfs', '-mkdir','-p', hdfs_file_path])
    
    
    
    def make_necessary_dirs(dir_to_create: str):
        # print(pathExists(dir_to_create))
        if pathExists(dir_to_create) == 1:
            hdfsMakedir(dir_to_create)
            return dir_to_create
        else:
            return "the folder already exists"
    
    
    list_of_dates =[]
    
    def generateDateFromThisYear(year) :    
    
        months = [1,2,3,4,5,6,7,8,9,10,11,12]
        dt = "" #str(d.date(2012, 1, 1))
        for month in months:
            no_of_days = monthrange(year, month)[1] # Taking only second Value as it returns number of weeks and no of days 
            for day in range(1,no_of_days+1) :
                x = d.date(year,month,day)
                y= x.strftime("%Y")+'/'+x.strftime("%m")+'/'+x.strftime("%d")
                list_of_dates.append(y)
    
        for i in list_of_dates:
            make_necessary_dirs(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2021-05-16
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2015-03-03
      相关资源
      最近更新 更多