Mac到Windows的Python

2 投票
3 回答
515 浏览
提问于 2025-04-16 22:33

我最近把一组几乎一模一样的程序从我的Mac电脑转移到了学校的Windows电脑上,虽然路径看起来是一样的(或者说最后的部分是一样的),但它们却无法正常运行。

import glob
import pylab
from pylab import *


def main():
    outfnam = "igdata.csv"
    fpout = open(outfnam, "w")
    nrows = 0
    nprocessed = 0
    nbadread = 0
    filenames = [s.split("/")[1] for s in glob.glob("c/Cmos6_*.IG")]
    dirnames = "c an0 an1 an2 an3 an4".split()
    for suffix in filenames:
        nrows += 1
        row = []
        row.append(suffix)
        for dirnam in dirnames:
            fnam = dirnam+"/"+suffix
            lines = [l.strip() for l in open(fnam).readlines()]
            nprocessed += 1
            if len(lines)<5:
                nbadread += 1
                print "warning: file %s contains only %d lines"%(fnam, len(lines))
                tdate = "N/A"
                irrad = dirnam
                Ig_zeroVds_largeVgs = 0.0
            else:
                data = loadtxt(fnam, skiprows=5)
                tdate = lines[0].split(":")[1].strip()
                irrad = lines[3].split(":")[1].strip()
                # pull out last column (column "-1") from second-to-last row
                Ig_zeroVds_largeVgs = data[-2,-1]
            row.append(irrad)
            row.append("%.3e"%(Ig_zeroVds_largeVgs))
        fpout.write(", ".join(row) + "\n")
    print "wrote %d rows to %s"%(nrows, outfnam)
    print "processed %d input files, of which %d had missing data"%( \
        nprocessed, nbadread)`

这个程序在Mac上运行得很好,但在Windows上我总是遇到:

 print "wrote %d rows to %s"%(nrows, outfnam)
    print "processed %d input files, of which %d had missing data"%( \
        nprocessed, nbadread)

写入文件名时写了0行

处理了0个输入文件,其中有一个缺少数据

在我的Mac上,我写入了144行到文件...

有没有人有什么建议?

3 个回答

0

你用的 s.split("/") 其实应该改成 s.split(os.pathsep)。我之前就因为这个吃过亏… :)

实际上,glob 在Windows上返回的路径是用 \,而在Mac OS X上是用 /,所以你在分割路径的时候需要用合适的分隔符,也就是 os.pathsep

2

我想了想,这个问题可能是因为在路径中使用了/。其实,Windows系统是用\来表示路径的。

os.path模块里有很多函数,可以帮助我们在不同系统中处理路径,使用起来更方便。

3

如果这个脚本没有报错,那么这段代码很可能返回的是一个空列表。

glob.glob("c/Cmos6_*.IG")

因为在Windows上使用正斜杠(/)的情况下,glob.glob运行得很好,所以问题很可能是它找不到文件。这通常意味着你提供的字符串中有某个地方出错了。请确保"c/Cmos6_*.IG"没有错误。

如果问题不是由这个引起的,那我就不知道为什么会这样了。

另外,当我试的时候,Windows上通过glob.glob返回的文件名中有反斜杠(\),所以你可能应该用"\\"来分割。

撰写回答