计数文件 Mac 与 Windows Python

Counting files Mac vs Windows Python

我有一个代码,用于计算目录中的文件数并从 .txt 文件中读取行。

该代码在我的 Mac 上运行良好,但在 Windows 上无法运行(即使我更改了路径)。这是 Windows 上的代码:

import glob
path = 'E:\calpy_em27_neu\spectra_out_demo0803\*'
files = glob.glob(path)

with open('info.txt', 'rt') as infofile:
    for count, line in enumerate(infofile):
        print count
print(len(files))

在 windows 我得到输出:

0
1
1
3
0

在 Mac 我得到(正确的)输出:

0
1
2
3
4

因为infofile中有四行,called目录中有四个文件。知道为什么这在 Windows 上无法正常工作吗?

也许您需要转义反斜杠字符。尝试其中之一:

path = r'E:\calpy_em27_neu\spectra_out_demo0803\*'
path = 'E:\calpy_em27_neu\spectra_out_demo\140803\*'
path = 'E:/calpy_em27_neu/spectra_out_demo/140803/*'