我有一个名称如下的文件列表:
20140911_085234.csv
20140912_040056.csv
所知的是第一部分是日期(第二部分是随机数)。如果我知道日期,我该如何打开正确的文件?
更新:每天有一个文件。
答案 0 :(得分:2)
正如@isedev所说,您可以使用fnmatch方法查找具有“日期”模式的所有文件。代码可能是这样的:
from fnmatch import fnmatch
import os
folder_path = '/home/Desktop/project'
all_files = os.listdir(folder_path)
content_file = 'Hello World'
_date = '20140911'
_pattern = _date + '*'
for file_name in all_files:
if fnmatch(file_name, _pattern):
with open(os.path.join(folder_path, file_name), 'wb') as f:
f.write(content_file)
我希望它可以帮到你!
答案 1 :(得分:1)
使用glob
:
import time
import glob
import os
def open_file_by_date(date):
path = "/path/to/file"
files = glob.glob1(path, date + "_*.csv")
for file in files:
with open(os.path.join(path, file), 'wb') as f:
#do your stuff with file
if __name__ == "__main__":
today = time.strftime("%Y%m%d")
open_file_by_date(today)