[英]How can I read files with similar names on python and then work with them?
[英]How can I read files with similar names on python, rename them and then work with them?
我已經在這里發布了同樣的問題,但遺憾的是我無法提出解決方案(即使你們中的一些人給了我很棒的答案,但其中大多數不是我想要的),所以我'我會再試一次,這次提供有關我正在嘗試做的事情的更多信息。
所以,我正在使用一個名為 GMAT 的程序來獲取一些輸出(帶有數值的 .txt 文件)。 這些輸出有不同的名稱,但因為我將它們用於不止一件事,所以我得到了這樣的東西:
GMATd_1.txt
GMATd_2.txt
GMATf_1.txt
GMATf_2.txt
現在,我需要做的是在我的代碼中使用這些輸出作為輸入。 我需要在腳本的其他功能中使用它們,並且由於我將有很多這些 .txt 文件,我想重命名它們,因為我不想像“./path/etc”那樣使用它們。
所以我想要的是編寫一個循環來獲取這些文件並在腳本內重命名它們,以便我可以在其他函數(循環外)中使用具有新名稱的這些文件。
因此,不必單獨這樣做:
GMATds1= './path/GMATd_1.txt'
GMATds2= './path/GMATd_2.txt'
我想寫一個循環來為我做這件事。
我已經嘗試過使用字典:
import os
import fnmatch
dict = {}
for filename in os.listdir('.'):
if fnmatch.fnmatch(filename, 'thing*.txt'):
examples[filename[:6]] = filename
這確實有效,但我不能在循環外使用字典鍵。
如果我理解正確,您會嘗試獲取名稱相似的文件(至少是重復出現的模式)並重命名它們。 這可以通過以下代碼完成:
import glob
import os
all_files = glob.glob('path/to/directory/with/files/GMAT*.txt')
for file in files:
new_path = create_new_path(file) # possibly split the file name, change directory and/or filename
os.rename(file, new_path)
glob
庫允許使用*
通配符搜索文件,因此可以使用特定模式搜索文件。 它列出了某個目錄中的所有文件(如果包含*
通配符作為目錄,則列出多個目錄)。 當您迭代文件時,您可以直接處理文件的輸入(正如您顯然打算做的那樣),也可以按照此代碼段所示重命名它們。 要重命名它們,您需要生成一個新路徑 - 因此您必須編寫create_new_path
函數,該函數采用舊路徑並創建一個新路徑。
從 python 3.4 開始,你應該使用內置的pathlib
包而不是os
或glob
。
from pathlib import Path
import shutil
for file_src in Path("path/to/files").glob("GMAT*.txt"):
file_dest = str(file_src.resolve()).replace("ds", "d_")
shutil.move(file_src, file_dest)
您可以使用
import os
path='.....' # path where these files are located
path1='.....' ## path where you want these files to store
i=1
for file in os.listdir(path):
if file.endswith(end='.txt'):
os.rename(path + "/" + file, path1 + "/"+str(i) + ".txt")
i+=1
它將源文件夾中的所有 txt 文件重命名為 1,2,3,....n.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.