我经常使用python来处理数据目录.最近,我注意到列表的默认顺序已经变为几乎荒谬的东西.例如,如果我在包含以下子目录的当前目录中:run01,run02,... run19,run20,然后我从以下命令生成一个列表:
dir = os.listdir(os.getcwd())
Run Code Online (Sandbox Code Playgroud)
然后我通常按此顺序获得一个列表:
dir = ['run01', 'run18', 'run14', 'run13', 'run12', 'run11', 'run08', ... ]
Run Code Online (Sandbox Code Playgroud)
等等.订单曾经是字母数字.但是这个新订单现在已经和我保持了一段时间.
什么是确定这些列表的(显示)顺序?
我正在尝试获取特定目录中的文件列表并计算目录中的文件数.我总是得到以下错误:
WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'
Run Code Online (Sandbox Code Playgroud)
我的代码是:
print len([name for name in os.listdir('/client_side/') if os.path.isfile(name)])
Run Code Online (Sandbox Code Playgroud)
我按照这里给出的代码示例.
我在Pyscripter上运行Python脚本,目录/ client_side/do存在.我的python代码在根文件夹中,并有一个名为"client_side"的子文件夹.有人可以帮我解决这个问题吗?
考虑以下代码:
files = sorted(os.listdir('dumps'), key=os.path.getctime)
Run Code Online (Sandbox Code Playgroud)
目标是根据创建时间对列出的文件进行排序.但是由于os.listdir只提供文件名而不是绝对路径,即os.path.getctime抛出异常
OSError: [Errno 2] No such file or directory: 'very_important_file.txt'
有这种情况的解决方法还是我需要编写自己的排序功能?
如何获取计算机系统上所有字体名称的列表?
我尝试在 Windows 上使用 os.scandir() 而不是 os.listdir() 来优化用 Python 编写的文件浏览功能。但是,时间保持不变,大约2分半钟,我不知道为什么。以下是原始和修改的功能:
os.listdir() 版本:
def browse(self, path, tree):
# for each entry in the path
for entry in os.listdir(path):
entity_path = os.path.join(path, entry)
# check if support by git or not
if self.git_ignore(entity_path) is False:
# if is a dir create a new level in the tree
if os.path.isdir( entity_path ):
tree[entry] = Folder(entry)
self.browse(entity_path, tree[entry])
# if is a file add it to the tree
if os.path.isfile(entity_path):
tree[entry] = File(entity_path)
Run Code Online (Sandbox Code Playgroud)
os.scandir() 版本: …
我正在尝试这样做:
import os
[x for x in os.listdir('.') if os.path.isfile(x)]
[x for x in os.listdir('dirname') if os.path.isfile(x)]
[x for x in os.listdir(os.path.abspath('dirname')) if os.path.isfile(os.path.abspath(x))]
Run Code Online (Sandbox Code Playgroud)
第一行工作:
[x for x in os.listdir('.') if os.path.isfile(x)]
Run Code Online (Sandbox Code Playgroud)
但接下来的两个:
[x for x in os.listdir('dirname') if os.path.isfile(x)]
Run Code Online (Sandbox Code Playgroud)
和
[x for x in os.listdir(os.path.abspath('dirname')) if os.path.isfile(os.path.abspath(x))]
Run Code Online (Sandbox Code Playgroud)
只是输出 []
为什么?
我计划获得一个巨大的数据文件夹。该文件夹的总大小约为2TB
,并且包含大约 200 万个文件。我需要对这些文件进行一些处理(主要是删除其中 99%)。
我预计由于数据大小会出现一些问题。我特别想知道Python是否能够os.listdir()
在合理的时间内正确列出这些文件。
例如,根据我的经验,在某些情况下,在 Ubuntu 上删除像这样的大文件夹可能会很痛苦。
Python:我想知道这个方法listdir在哪里,因为他不在模块os.py中.在这个模块中没有一个方法:
def listdir ()
Run Code Online (Sandbox Code Playgroud) 所以我想在Python中抓取目录下的第一个文件。我知道我可以这样做:
first_file = [join(path, f) for f in os.listdir(path) if isfile(join(path, f))][0]
Run Code Online (Sandbox Code Playgroud)
但它很慢。有没有更好的解决办法?谢谢!
这是来自多个文件夹/子文件夹(同一驱动器)的文件名列表。例子 :
C:\Test\GO\abc.csv
C:\Test\TEST2\TER.abc.csv
C:\Test\CAR\abc.cvs
Run Code Online (Sandbox Code Playgroud)
我需要将“C:\Test”作为上述文件列表的共享根文件夹。已经有 python 函数了吗?