简体   繁体   English

Python os.listdir()一直在跳过一些文件?

[英]Python os.listdir() keeps skipping over some files?

I have written a Python script for writing out all the file names in a given directory to a file for processing, and it works perfectly on my machine. 我编写了一个Python脚本,用于将给定目录中的所有文件名写入文件进行处理,并且它在我的机器上完美运行。 But when I try to run it on the target machine, it skips some of the files. 但是当我尝试在目标机器上运行它时,它会跳过一些文件。 Here's a shell of the code I am using: 这是我正在使用的代码的shell:

for line in os.listdir(d):
    f.write(line + "\n")

As I said, this works as advertised on my system, but not on the target system. 正如我所说,这在我的系统上宣​​传,但不在目标系统上。 The data is the same; 数据是一样的; I transferred it from the target system to mine for preliminary testing while writing the script, and I've inspected both data sources to verify that nothing got lost in the transfer. 我在编写脚本的同时将它从目标系统转移到我的进行初步测试,并且我检查了两个数据源以验证传输中没有丢失。 Output from my system looks like: 我系统的输出如下:

filename.f0000
filename.f0001
filename.f0002
filename.f0003
...

But output from the target system looks like: 但目标系统的输出如下:

filename.f0000
filename.f0003
filename.f0008
filename.f0017
...

I am on a 64-bit Windows PC running Cygwin, and it has Python version 2.7.5 installed. 我在运行Cygwin的64位Windows PC上安装了Python 2.7.5版本。 The target system is a Cray XK7 running OpenSuse, and it has Python version 2.6.8 installed. 目标系统是运行OpenSuse的Cray XK7,它安装了Python 2.6.8版。

Could this be a difference between the two versions of Python, or rather the two different operating systems? 这可能是两个版本的Python之间的区别,还是两个不同的操作系统?

You can try to use the built in sorted method, eg 您可以尝试使用内置排序方法,例如

for line in sorted(os.listdir(d)):
    f.write(line + "\n")

Here's some more information from python documentation that you might find helpful: https://docs.python.org/2/library/os.html 以下是python文档中的一些您可能会发现有用的信息: https//docs.python.org/2/library/os.html

os.listdir(path) os.listdir(路径)

Return a list containing the names of the entries in the directory given by path. 返回一个列表,其中包含path给出的目录中的条目名称。 The list is in arbitrary order . 该列表按任意顺序排列 It does not include the special entries '.' 它不包括特殊条目'。' and '..' even if they are present in the directory. 和'..'即使它们存在于目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM