在Windows CMD中运行Python 3.2脚本时文件I/O问题,但在IDLE中正常
我是一名Python新手,在使用cmd命令提示符运行带有open()函数的程序时遇到了问题。在Python的IDLE环境中,代码运行得很好,但每次我双击脚本图标(我已经把.py文件关联到Python)时,就会出现一些错误,比如:
找不到文件 test.txt(我输入了内容)
文件 2 找不到 atest2.txt(我输入了内容)
追踪(最近的调用最后):
文件 "C:\Users\Matthew\Desktop\file_io\find_differences_in_files.py",第 3 行,
在 <模块> 中
f=open(c,"r") # 打开 c
IOError: [Errno 22] 无效参数: 'test.txt\r'
类似的问题在多个相似的程序中也出现了,不过这里有一段代码(顺便说一下,这段代码用于找到两个.txt文件中的第一个不同之处),在IDLE中能正常工作,但在cmd中却不行。有没有人知道出了什么问题?
c=input("what file") # get file 1
d=input("file 2") # get file 2
f=open(c,"r") # open c
g=open(d,"r") # open d
p=f.readlines() # get every line of f
q=g.readlines()
i=0
while i<len(p) and i<len(q):
if p[i]!=q[i]:
break # stop counting up
i+=1
x=p[i] # store different line
y=q[i] # store different line
j=0
while j<len(x) or i<len(y):
if x[j]!=y[j]:
break # stop counting up
j+=1
print("The difference is in line %s column %s" % (i+1,j+1))
c=input("press enter")
1 个回答
1
你没有正确处理行结束符。IDLE给你的行结束符是一种格式,而cmd.exe则用另一种格式。
我建议你在这种情况下去掉输入两端的空白字符。