将文件复制到新文件夹并在 python 中重命名

发布于 2025-01-09 02:59:32 字数 223 浏览 3 评论 0原文

我正在尝试将 xls 文件复制到新文件夹并将其重命名为 xlsx 文件,但出现几个错误。 我想更改名称,因为 xls 文件可能已损坏。 输入文件由用户给出,我想在输入文件所在的路径中创建新文件夹,并将文件复制到新文件夹中。

我可以创建新文件夹,但无法将文件复制到那里,而且如果我重命名其中的文件,则只有文件仍然损坏。

我想要一个解决方案,如果复制并重命名文件,则 .xlsx 文件打开时不会弹出任何窗口。

I’m trying to copy an xls file to a new folder and there renaming it as xlsx file but I’m getting several errors.
I want to change the name because the xls file could be corrupt.
The input file is given by the user and I want to create the new folder in the same path as the input file is in and copy the file in the new folder.

I’m able to create new folder but unable to copy file there moreover if I rename the file therein only the file still remains corrupt.

I want a solution such that if the file is copied and renamed the .xlsx file opens without any pop up.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过去的过去 2025-01-16 02:59:32

如果你的文件损坏了,没有办法通过更改名称来修复它,下面的代码只会帮助你复制文件并创建文件夹:

import os
from shutil import copyfile

if not os.path.exists("folder"):
    os.mkdir("folder")

target = os.path.join(os.getcwd(), "folder")

filename = input("filename: ")

if os.path.exists(filename):
    target_filename = filename.replace("xls", "xlsx")
    copyfile(filename, os.path.join(target, target_filename))
    print("success")
else:
    print("failure")

If your file is corrupted, there is no way to fix it by changing the name, the following code will only help you copy the file and create the folder:

import os
from shutil import copyfile

if not os.path.exists("folder"):
    os.mkdir("folder")

target = os.path.join(os.getcwd(), "folder")

filename = input("filename: ")

if os.path.exists(filename):
    target_filename = filename.replace("xls", "xlsx")
    copyfile(filename, os.path.join(target, target_filename))
    print("success")
else:
    print("failure")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文