簡體   English   中英

如何在python中使用文本文件重命名文件名

[英]How to rename file names using text file in python

我需要使用文本文件中的新名稱引用重命名文件夾中的一堆文件。 你能舉一個例子嗎?

我在文本文件中的新名稱:

1BA
1BB
1BC
1BD
1BE
1BF
1C0
1C1
1C2
1C3

像這樣。

更新代碼:

import csv
import os

with open('names.txt') as f2:
         filedata = f2.read().split(",")
         os.rename(filedata[0].strip(), filedata[1].strip())
f2.close()
f2 = open ('Lines.txt','w')
f2.write(filedata)
f2.close()

如何使用 CSV(逗號分隔)文件以oldPath, newPath格式輸入並執行以下操作:

import csv
import os

with open('names.csv') as csvfile:
     reader = csv.reader(csvfile)
     for row in reader:
         oldPath = row[0]
         newPath = row[1]
         os.rename(oldPath, newPath)

或者,如果您想將文件移動到另一個目錄/文件系統,您可以查看shutil.move

# Create old.txt and rename.txt
# Do not include file path inside the txt files
# For each line, write a filename include the extension

from pathlib import Path
import os
import sys

print("enter path of folder")
path = input()

oldList = []
with open(path + "\\old.txt", "r", encoding="utf8", errors='ignore') as readtxt:
    for f in readtxt:
        fname = f.rstrip()
        oldList.append(fname)

# i is index of oldList
i = 0
newList = []
with open(path + "\\rename.txt", "r", encoding="utf8", errors='ignore') as readtxt:
    for f in readtxt:
        newName = f.rstrip()
        os.rename(path + "\\" + oldList[i], path + "\\" + newName)
        i += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM