【问题标题】:how to rename files in a folder with the files name in file.txt in python?python - 如何使用python中file.txt中的文件名重命名文件夹中的文件?
【发布时间】:2022-01-10 08:36:13
【问题描述】:

我的代码

import os

file1 = open('names.txt', 'r')
Lines = file1.readlines()
path = "/home/kingj/loop/"

for line in Lines:
    for filename in os.listdir(path):
        md=path + line.strip() 
        ms=path + filename
        os.rename(ms, md)

但我最终只得到了一个文件。为什么?

【问题讨论】:

  • 你认为你的 2 个嵌套循环是做什么的?
  • 哦,这就是问题所在,但我现在该怎么办?请问有什么帮助吗?第二个循环应该只运行一次
  • 80K 名称和 80K 文件!

标签: python list loops for-loop rename


【解决方案1】:
import os
 
path = '/home/kingj/gipfa/mfcc_2.0_40'

files = os.listdir(path)

i = 0
pathh = "/home/kingj/Recorders/new/"
# Strips the newline character
for filename in os.listdir(pathh):
        md=pathh + files[i]
        ms=pathh + filename
        os.rename(ms, md)
        i+=1

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 2022-06-27
  • 2015-08-26
  • 2020-05-17
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多