社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

从给定的.txt文件python读取文件名

kishore ezio • 6 年前 • 1414 次点击  

我是巨蟒的新手。

我试图写一个程序,它将从.txt文件中读取文件。

(这意味着我有一个“filenames.txt”文件,并且该文件中有文件名及其路径) 如何从该.txt文件中读取这些文件名并获取文件的创建日期?

下面是我提出的代码:

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)

事先谢谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30405
 
1414 次点击  
文章 [ 3 ]  |  最新文章 6 年前
mwen1993
Reply   •   1 楼
mwen1993    6 年前

您可以使用以下方法检查文件创建时间:

import os, time
time.ctime(os.path.getctime('your_full_file_path'))
Andrew
Reply   •   2 楼
Andrew    6 年前

如果它们是这样的格式:【文件名】【路径】在每一行,我建议如下:

f = open('filenames.txt', 'r').read().splitlines()

这将从文件中读取,然后将其拆分为行

f = [x.split(' ') for x in f]

它是一种迭代f的缩短方法,f是一个字符串列表,然后在空间中拆分每个字符串,使其成为[文件名,路径]

这里有些复杂:

import os
from datetime import datetime
from time import strftime
datetime.fromtimestamp(os.path.getctime('filenames.txt')).strftime('%Y-%m-%d %H:%M:%S')

所有使用的模块都是内置的

祝你好运

Shaahin Shemshian
Reply   •   3 楼
Shaahin Shemshian    6 年前

通过此操作,您可以打开一个文件:

file = open('path/to/filenames.txt')

假设数据每行写入一个文件名,您可以这样从文件中读取:

filename = file.readline()

那么为了知道创造的时间,你可以 import os 使用 stat 功能。这个函数会告诉你 st_atime 上次访问时间, st_mtime 上次修改时间和 st_ctime 作为创建时间。看一看 here :

import os
stat = os.stat(filename)
creation_time = stat.s_ctime

对于在文件名末尾注释空白,可以使用rstip。 所以,总的来说,它看起来是这样的:

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()