I am new to python.
I was trying to write a program that will read files from a .txt file.
(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?
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. this function will tell you st_atime
which is last accessed time, st_mtime
as last modified time and st_ctime
as creation time. 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. 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]
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.