簡體   English   中英

匹配文件名並將其保存到python中的變量

[英]Matching filename and saving it to a variable in python

有誰知道如何匹配文件名,然后將其保存到變量中?

例如,我有多個文件正在保存在一個文件夾中。 它們都以相同的名稱開頭。 “ AmountFile”都是以“ AmountFile”開頭,但文件名不同,其余部分是日期。

因此,所有內容一開始看起來都像AmountFile,但隨后看起來像AmountFile20141020,依此類推。

我想匹配文件名,將其保存在變量中,以便可以在os.rename函數中使用它。

File1 = AmountFile123
File2 = AmountFile321
File3 = AmountFile456
File4 = AmountFile789

我想匹配它們,以便可以在變量中使用它。

def main():
d = 'D:\Applications\IMP\Something'
for filename in os.listdir(d):
    title = 'Import_ABC'
    oldFile = 'AmountFile'
    if filename.endswith(".csv"):
        os.rename(oldFile,title+".csv")

main()

WindowsError: [Error 2] The system cannot find the file specified

當文件夾中的重命名文件完成后,我的系統會自動將其重命名到另一個文件夾中,從中將它們導入到我們的數據庫中。 問題在於示例文件中的開始相同,但結束不同,這使得運行該函數變得困難。 對於OldFile變量,我需要匹配一個可以保存的文件名,而不是'AmountFile'

import glob

filenames = glob.glob("AmountFile*")

然后filenames將是當前目錄中所有名稱以AmountFile開頭的所有文件的列表。

暫無
暫無

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

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