Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python打开动态更改的文件路径_Python_Regex_File_Csv - Fatal编程技术网

Python打开动态更改的文件路径

Python打开动态更改的文件路径,python,regex,file,csv,Python,Regex,File,Csv,我有一个整天都在更新的文件,该文件的名称随着文件更新时间的签名而更改 e、 g \文件夹\todolist\grocerylist_2015-12-30-093000.csv 如何在不手动更新完整文件路径的情况下用python打开此文件?也许您可以使用python模块打开前缀为grocerylist的文件 import glob path = glob.glob('/folder/todolist/grocerylist_*.csv')[0] 您可以使用模块来处理此问题 import glob

我有一个整天都在更新的文件,该文件的名称随着文件更新时间的签名而更改

e、 g

\文件夹\todolist\grocerylist_2015-12-30-093000.csv


如何在不手动更新完整文件路径的情况下用python打开此文件?

也许您可以使用python模块打开前缀为
grocerylist的文件

import glob
path = glob.glob('/folder/todolist/grocerylist_*.csv')[0]
您可以使用模块来处理此问题

import glob
file_path = glob.glob('\\folder\\todolist\\grocerylist_*.csv')[0]
如果有更多文件,而您只需要最新的文件,则可以对最后一个文件进行排序和获取:

file_path = sorted(glob.glob('\\folder\\todolist\\grocerylist_*.csv'))[-1]

如果您想查看文件创建,我建议您使用类似的方法,这将始终为您提供与您的模式匹配的最新创建的文件:

import sys
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class Handler(PatternMatchingEventHandler):
    def __init__(self, regexes):
        super(Handler, self).__init__(regexes)

    def process(self, event):
        print(event.src_path, event.event_type)


    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    import os
    pth = sys.argv[1:]
    observer = Observer()
    pth = pth[0] if pth else "./"
    observer.schedule(Handler([os.path.join(pth, "grocerylist_*.csv")]), path=pth[0] if pth else './')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
当创建与您的模式匹配的文件时,将调用\u created
调用
process
,您可以在该方法中执行任何您喜欢的操作:

~$ python3 watch.py  & 
[15] 21005
padraic@home:~$ touch grocerylist_12345.csv
padraic@home:~$ ./grocerylist_12345.csv created

如果要打开文件,请在过程中打开。

它是目录中唯一的文件,还是保留了较旧的版本?假定只有一个文件与模式匹配,如果有更多文件,则需要最新创建的文件,该文件将涉及排序