【问题标题】:Count how many text files in a directory using python 2.7 and edit them使用python 2.7计算目录中有多少文本文件并编辑它们
【发布时间】:2015-05-14 15:17:23
【问题描述】:

我需要帮助计算 python 中的目录/文件夹 (Windows 7) 中的文件数量,所以如果有超过 20 个 .txt 文件,我可以删除一些,总有 20 个 .txt 文件。如果您使用 python 创建另一个,它会删除最旧的。

任何答案都会有所帮助,谢谢。

import os
(_, _, my_files) = os.walk("C:\\Users\\guest.user\\task2").next()
amount = len([f for f in my_files if f.endswith('.txt')])

print amount

if amount > 20:
#This is my next problem - needs to truncate the file once there is more than 20

【问题讨论】:

  • 你能粘贴一些你到目前为止尝试过的代码吗?
  • 当您显然对子目录不感兴趣时​​,为什么还要使用 os.walk? os.listdir 为您提供一个目录中的所有文件。 glob.glob 甚至可以让你指定一个模式,比如 glob.glob('*.txt')。

标签: python python-2.7 variables counting


【解决方案1】:

统计txt文件数

import os


(_, _, my_files) = os.walk('some_directory').next()
print len([f for f in my_files if f.endswith('.txt')])

统计 txt 文件并删除前 10 个以外的文件

import os


(_, _, my_files) = os.walk('some_directory').next()
if len([f for f in my_files if f.endswith('.txt')]) > 10:
    for f in my_files[9:]:
        os.remove(os.path.join('some_directory', f))

计算 txt 文件并删除 x 个文件后的任何内容

import os


my_directory = 'some_directory'
max_files = 20

(_, _, my_files) = os.walk(my_directory).next()

if len([f for f in my_files if f.endswith('.txt')]) > max_files:
    for f in my_files[max_files-1:]:
        os.remove(os.path.join(my_directory, f))

【讨论】:

  • 如果我有 21 个文件,它会删除 1 个,你能这样做吗?
  • @SirLuca 是的,让我知道我刚刚添加的代码是否有效(最后一个代码)。
  • 我给了我这个错误:NameError: name 'max_files' is not defined @Mr_Spock
  • 别担心 - 已修复,谢谢
  • @SirLuca 我的代码有错误吗?如果是这样,请告诉我,以便我修复它。这是一个公共论坛,因此其他人可能需要同样的帮助!答案应该是正确的。 :-)
【解决方案2】:

对于大小,请使用以下内容:

import os

filesInDir = os.listdir(myPath) # returns a list with all the file names in that directory
numOfFilesInDir = len(filesInDir)

要删除文件,请使用以下命令:

import os

os.delete(pathToFile)

检查文件的创建时间:

import os

(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(pathToFile)
# ctime is the creation time of the file.

创建文件:

open(filePath, 'w')

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多