【问题标题】:How to move numbered files into numbered folders using Python?如何使用 Python 将编号文件移动到编号文件夹中?
【发布时间】:2018-02-28 07:59:11
【问题描述】:

我有一系列名为mesh1mesh2mesh3 等的文件。我想创建相应的文件夹,比如folder1folder2folder3等等。我还想将文件放入文件夹中。例如,mesh1 应该进入 folder1mesh2 应该进入 folder2,等等。

这是我用来创建文件夹的代码:

for i in lst:
    os.makedirs("/home/tianxiangwang/Desktop/Simulation/File{}".format(i))

如何将文件移动到文件夹中?我试过了,但它不起作用:

os.rename("/home/tianxiangwang/Desktop/Simulation/Mesh{}.txt".format(i), "/home/tianxiangwang/Desktop/Simulation/File{}/Mesh{}.txt".format(i))

【问题讨论】:

  • 如果你的字符串中有两个 {},那么 .format 需要两个参数 :)

标签: python file move directory


【解决方案1】:

以下代码对我有用。

for item in items:
    os.makedirs("/home/tianxiangwang/Desktop/Simulation/"+str(item))
    fil="/home/tianxiangwang/Desktop/Simulation/"+str(item)+"/"+str(item)+".txt"
    os.rename("/home/tianxiangwang/Desktop/Simulation/"+str(item)+".txt",fil)

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多