使用非SCII字符文件名(emojis)在Python中操作文件

2024-05-14 10:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个IFTTT集成,可以将子Reddit中的图像拉到我电脑上的dropbox中。它的工作方式是,文件名就是Reddit帖子的标题。这意味着名称中有很多非ascii字符,例如emojis和其他字符,有时还有超过最大文件名大小的非常长的名称。我试图检查该目录中所有文件的修改时间,并使用Python2.7删除超过x小时的文件

我已经找到了一种获取长文件名的方法,方法是在文件路径前面加上\\?\,告诉windows允许长文件名。然而,现在我陷入了另一个问题,试图在带有表情符号的文件上添加os.stat

文件名示例:

❤️❤️❤️
A selfie with my little queen ❤️
Our beautiful Lily, aged ~12. Short on teeth, podgy, gets crap caught in her fur and I think she’s going deaf but we wouldn’t have her any other way. She’s mellowed out a lot in her old age but will still run around the house at 2am.

这是我目前的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, time, os, time

MediaPath = sys.argv[1]
cleanup = sys.argv[2]

now = time.time()
for media in os.listdir(MediaPath):
    mediaFile = os.path.join(MediaPath, media)
    fileTime = os.stat("\\\\?\\" + mediaFile).st_mtime
    #preferred deletion time in hours times 60 mins times 60 seconds to get seconds

    if fileTime < now - int(cleanup) * 60 * 60:
        if os.path.isfile(mediaFile):
            os.remove(mediaFile)
            print("Media removed: " + mediaFile)
    else:
        print("Media NOT removed: " + mediaFile)

我传入了两个参数,文件的路径和清理时间(以小时为单位)

我得到一个错误:WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '\\\\?\\C:\\Users\\USER\\Pictures\\aww\\A selfile with my little queen ??.jpg'


Tags: 文件方法in名称timeos文件名sys

热门问题