简体   繁体   English

如何从目录中的文件名中提取字符?

[英]How to extract characters from file names in a directory?

Essentially, if I have a file:基本上,如果我有一个文件:

"Field_20130515-212300"

I want to extract the date 20130515-212300 .我想提取日期20130515-212300 I have a method, but it is inelegant.我有一个方法,但它是不雅的。 Just wondering if there's a better way to do this.只是想知道是否有更好的方法来做到这一点。

times = os.listdir("path\\to\\your\\file")
for idx, time in enumerate(times):
    time[idx] = time[-15:]

This has been solved using list comprehension thanks to @alani.由于@alani,这已经使用列表理解解决了。

times = os.listdir("path\\to\\your\\file")
times = [t.split("_")[1] for t in times]

Seems simple to do it in a one liner..在一个班轮中做这件事似乎很简单..

import os
times = [file[-15:] for file in os.listdir('path\\to\\your\\file')]

Or with split()或者用 split()

import os
times = [file.split('_')[1] for file in os.listdir('path\\to\\your\\file')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用正则表达式从给定目录中提取文件名 - Extract file names from a given directory with regex 从Python中的动态文件路径中提取目录名称 - Extract Directory Names from Dynamic File Paths in Python 如何从目录中的文件夹名称中提取后缀字符串? (蟒蛇) - How to Extract A String of the Suffix from Folder Names in a Directory? (Python) 从python中的文件中提取名称 - Extract names from file in python 从目录中提取文件名并根据其扩展名进行分类 excel | 使用 PYTHON - Extract File names from directory and classify on the basis of its extension in excel | Using PYTHON 如何保存,然后从dataframe中的文件名中提取一些信息 - how to save and then extract some information from the file names in dataframe 如何正确地从 .txt 文件中提取列名 - How to extract column names from .txt file properly 如何从文件的每一行提取字符和数字? - How to extract characters and numbers from every line of a file? 如何存储目录中的所有文件名并保存在excel中? - How to store all file names from the directory and save it in excel? 如何在不维护 Python 中的目录结构的情况下从 zip 中提取文件? - How to extract file from zip without maintaining directory structure in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM