[英]read filenames from a given .txt file python
I am new to python. 我是python的新手。
I was trying to write a program that will read files from a .txt file. 我正在尝试编写一个程序,该程序将从.txt文件读取文件。
(that means I have a 'filenames.txt' file and have filenames with their paths in that file) How can I read those file names from that .txt file and get the date the file was created? (这意味着我有一个'filenames.txt'文件,并且在该文件中具有其路径的文件名)如何从该.txt文件中读取这些文件名并获取文件的创建日期?
Heres the code I came up with: 这是我想出的代码:
import sys, os
import pathlib
# list of filenames with their paths separated by comma
file_list = []
# input file name which contains list of files separated by \n
with open ('filenames.txt' , 'r+' ) as f :
list_file = f.readlines().splitlines()
input_list = file_list + list_file
def file_check(input_list):
if input_list is none:
print ("input_list is null")
print (input_list)
Thanks in advance. 提前致谢。
by this you can open a file: 通过这个你可以打开一个文件:
file = open('path/to/filenames.txt')
assuming data is written one file name per line you can read from your file like this: 假设数据每行写一个文件名,您可以像这样从文件中读取:
filename = file.readline()
then for knowing the time of creation you can import os
and use stat
function. 然后,为了知道创建时间,可以
import os
并使用stat
函数。 this function will tell you st_atime
which is last accessed time, st_mtime
as last modified time and st_ctime
as creation time. 该函数将告诉您
st_atime
为最后访问时间, st_mtime
为最后修改时间, st_ctime
为创建时间。 take a look at here : 在这里看看:
import os
stat = os.stat(filename)
creation_time = stat.s_ctime
for ommiting whitespaces at the end of the filenames you can use rstip. 要在文件名末尾省略空格,可以使用rstip。 So, altogether it will look like this:
因此,总共看起来像这样:
import os
file = open('path/to/filenames.txt')
filename = file.readline()
while filename:
stat = os.stat(filename.rstrip())
creation_time = stat.st_ctime
print(creation_time)
filename = file.readline()
If they are in this format: [filename] [path] on each line i suggest the following: 如果它们采用以下格式:每行的[文件名] [路径]我建议以下内容:
f = open('filenames.txt', 'r').read().splitlines()
This will read from the file and then split it into lines 这将从文件中读取,然后将其分成几行
f = [x.split(' ') for x in f]
It is a shorten way of iterating over f which is a list of string and then split each string at the space so it will be [filename, path] 这是迭代f的一种简便方法,f是一个字符串列表,然后在空格处分割每个字符串,因此它将是[filename,path]
Here things get a little bit complicated: 这里的事情有点复杂:
import os
from datetime import datetime
from time import strftime
datetime.fromtimestamp(os.path.getctime('filenames.txt')).strftime('%Y-%m-%d %H:%M:%S')
All the modules used are builtin 所有使用的模块都是内置的
Good Luck 祝好运
You can check file creation time by using: 您可以使用以下方法检查文件创建时间:
import os, time
time.ctime(os.path.getctime('your_full_file_path'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.