python拖拽文件问题

在把文件拖拽到窗口后,获取的文件路径不是系统路径,无法使用OS模块获取文件的信息,
代码如下:
import os
from tkinter import messagebox
import windnd
from tkinter import *
window_width = 200
window_height = 200


def window_init(window, width, height):
    ws = window.winfo_screenwidth()
    hs = window.winfo_screenheight()
    # 居中
    x = (ws / 2) - (width / 2)
    y = (hs / 2) - (height / 2)
    window.geometry("%dx%d+%d+%d" % (width, height, x, y))
    window.resizable(False, False)
    window.overrideredirect(True)
    window.attributes('-topmost', 'true')


def message(title, msg, parent=None):
    messagebox.showinfo(title=title, message=msg, parent=parent)


def dragged_files(files):
    print(files)
    a = str(files[0])
    b = a.rfind('\\')
    b1 = a.rfind('b')
    c1 = a[b1 + 2: -1]
    print(c1)
    fs = os.stat(c1)


root = Tk()
window_init(root, window_width, window_height)
windnd.hook_dropfiles(root, func=dragged_files)
root.mainloop()
报错如下:

img

获取的文件路径:

img

实际的文件路径:
F:\xfmovie\桌面\1.txt

这是由于获取到的文件路径是字节类型(b'F:\xfmovie\llxd7\xc0\xc3\xe6\1.txt'),而 os.stat() 方法需要的是字符串类型的路径。可以使用 python 的 bytes.decode() 方法将字节类型转换为字符串类型。


def dragged_files(files):
    msg = '\n'.join((item.decode('gbk') for item in files))
    print(msg)
    fs = os.stat(msg)

img

将37修改为如下,增加一个 force_unicode=True就行了

windnd.hook_dropfiles(root, func=dragged_files,force_unicode=True)

多个文件同时拖拽也可以实现,如图

img

获取的文件路径是相对路径,不能用os模块获取文件信息。需要使用os.path.abspath(filepath)函数将相对路径转换为绝对路径。
可以在dragged_files函数中对文件路径进行转换,代码如下:

scss


def dragged_files(files):
    print(files)
    a = str(files[0])
    c1 = a[b1 + 2: -1]
    abs_file_path = os.path.abspath(c1)
    fs = os.stat(abs_file_path)

这样就可以使用os模块获取文件信息了

在拖拽事件中,获取的文件路径是使用的Windows下的文件路径格式,即使用反斜杠''代替正斜杠'/'。而在Python中使用的是正斜杠。所以需要将获取的文件路径中的反斜杠替换成正斜杠,方法如下:

def dragged_files(files):
    file_path = files[0].replace('\\', '/')
    print(file_path)
    fs = os.stat(file_path)
    ...

还有另外一种方法是使用pathlib库中的Path类,它提供了将Windows下的文件路径格式转换成Python中使用的文件路径格式的方法,方法如下:

from pathlib import Path
def dragged_files(files):
    file_path = Path(files[0])
    print(file_path)
    fs = os.stat(file_path)
    ...


这样就可以正确的获取文件的信息了。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^