【问题标题】:Moving files conditionally using shutil使用shutil有条件地移动文件
【发布时间】:2020-12-16 16:53:12
【问题描述】:

我正在尝试将文件从源目录移动到 linux 中的目标目录,这些文件以 .text 扩展名结尾,时间戳使用 shutil 但有些无法正常工作,看起来我做错了什么。

以下是文件所在的源目录:

$ ls -l /samba/smb_out/
-rw-r-----. 1 user1 tam 266852 Dec 16 21:41 fostert.20201215.text
-rw-r-----. 1 user1 tam 266852 Dec 16 21:41 fostert.20201216.text

测试代码:

>>> tm_src = time.strftime("%Y%m%d")
>>> tm_dst = time.strftime("%Y%m%d-%H:%M:%S")
>>> src = "/samba/smb_out/"
>>> dst = "/samba/script_logs/"
>>> outfile = ( src + tm_src + ".text")
>>> text_files = [el for el in os.listdir(src) if el.endswith(".text") and path.isfile(path.join(src, el))]
>>> for file in text_files:
    shutil.move(path.join(src, file ), dst + "-" + tm_dst + ".log")
    
'/samba/script_logs/-20201216-21:32:59.log'
'/samba/script_logs/-20201216-21:32:59.log'

期望的应该是:

'/samba/script_logs/fostert.20201215.text-20201215-21:32:59.log'
'/samba/script_logs/fostert.20201215.text-20201216-21:32:59.log'

知道我在这里做错了什么。

【问题讨论】:

    标签: python python-3.x linux shutil


    【解决方案1】:

    下面应该对你有用,你只是错过了 for 循环中的 file

    >>> for file in text_files:
          shutil.move(path.join(src, file ), dst + file + "-" + tm_dst + ".log")
    

    【讨论】:

    • 谢谢卡恩库马尔,我会试试的。
    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多