簡體   English   中英

如何檢查python中是否存在帶有*的文件?

[英]How do I check if a file exists with * in python?

我正在嘗試檢查文件是否存在,以便我可以讀取它。 關鍵是我不知道文件上的數字是多少。 一次應該只存在一個文件,但名稱會隨着我寫入文件(在代碼的另一部分)而更新,因此我不知道執行這段代碼時的確切數字是多少。

N=0
if os.path.exists('*somefile.txt'): #if the file exists, read it
    print("found Nsomefile.txt")
    filename = '*somefile.txt'
    something=np.loadtxt(filename)
    N = int(filename.split('s')[0]) #save the N from the filename
else: #otherise, preallocate memory for something
    something = np.empty((x,y))  
print(N,"of some thing")

在我的目錄中,我可以看到那里的文件 ('32somefile.txt') 但代碼仍然打印0 of some thing

您可能應該在這里使用 glob 而不是 os 函數。

Glob 還支持 * 字符,因此它應該適合您的用例。

謝謝大家! 我忘記了 glob。 (我在代碼的另一部分( facepalm )中使用它)。 現在看起來像:

import numpy as np
from glob import glob
N=0
if glob('*somefile.txt'): #if the file exists, read it
    print("found Nsomefile.txt")
    filename = glob('*somefile.txt')[0]
    something=np.loadtxt(filename)
    N = int(filename.split('s')[0]) #save the N from the filename
else: #otherise, preallocate memory for something
    something = np.empty((x,y))  
print(N,"of some thing")

哪個輸出

found Nsomefile.txt
32 of some thing

暫無
暫無

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

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