pycharm 终端并运行给出不同的结果 [英] pycharm terminal and run giving different results
问题描述
使用 Pycharm 编写用于加载和格式化固定宽度文件的 python 脚本,当我在终端(在 Pycharm 内或本地)中运行脚本和在 Pycharm 中使用运行选项时,我得到了不同的结果.为什么会出现这种情况,哪个是正确的?
with open('uk_dcl_mrg.txt', 'rb') as f:ct = 0对于 f 中的行:ct += 1####输出####for i in layout: ## 循环创建字典headerdict[i[0]] = line[i[1]:i[2]]if (headerdict['CORP-STATUS-IND'] == "\x9f"):headerdict['CORP-STATUS-IND'] = '0'elif headerdict['CORP-STATUS-IND'] == '?':headerdict['CORP-STATUS-IND'] = '1'别的:headerdict['CORP-STATUS-IND'] = '2'打印(标题)如果 ct >= 6:休息
终端输出
'CORP-STATUS-IND': '0',
在 Pycharm 的运行选项中输出
'CORP-STATUS-IND': '2',
终端输出是我所期望的.
当我不确定时,我通常不会回答,但在这里我很确定:
您可能正在运行 2 个不同的解释器版本.控制台中的 Python 2 和 PyCharm 中的 Python 3.
通过在脚本中插入以下行来确认:
print(sys.version)
问题是这一行:
with open('uk_dcl_mrg.txt', 'rb') as f:
由于您以二进制形式打开文件,因此在 Python 3 中,行是二进制的,而不是字符串,因此将它们与字符串进行比较总是失败.
<预><代码>>>>b'\x9f'=='\x9f'错误的>>>b'\x9f'[0]159>>>'\x9f'[0]'\x9f'在 Python 2 中,无论文件打开模式如何,行都是 str
类型,这说明它有效.
像这样修复你的代码:
with open('uk_dcl_mrg.txt', 'r') as f:
它适用于所有版本的python.但我建议你放弃 Python 2,除非你被绑定到 Python 2 并默认安装 Python 3.
Using Pycharm to write a python script for loading and formatting a fixed width file I'm getting different results when I run the script in terminal (within Pycharm or locally) and when using the run option in Pycharm. Any reason why this is the case and which is correct?
with open('uk_dcl_mrg.txt', 'rb') as f:
ct = 0
for line in f:
ct += 1
#### OUTOUT ####
for i in layout: ## Loop to create dictionary
headerdict[i[0]] = line[i[1]:i[2]]
if (headerdict['CORP-STATUS-IND'] == "\x9f"):
headerdict['CORP-STATUS-IND'] = '0'
elif headerdict['CORP-STATUS-IND'] == '?':
headerdict['CORP-STATUS-IND'] = '1'
else:
headerdict['CORP-STATUS-IND'] = '2'
print(headerdict)
if ct >= 6:
break
Output in Terminal
'CORP-STATUS-IND': '0',
Output in the run option of Pycharm
'CORP-STATUS-IND': '2',
The terminal output is what I am expecting.
I'm usually not answering when I'm not sure but here I'm pretty sure:
You're probably running 2 different interpreter versions. Python 2 in your console, and Python 3 in PyCharm.
Confirm it by inserting the following line in your script:
print(sys.version)
The problem is this line:
with open('uk_dcl_mrg.txt', 'rb') as f:
since you're opening the file as binary, in Python 3, lines are binary, not string, so comparing them to string always fails.
>>> b'\x9f'=='\x9f'
False
>>> b'\x9f'[0]
159
>>> '\x9f'[0]
'\x9f'
In Python 2, the lines are of str
type regardless of the file open mode, which explains that it works.
Fix your code like this:
with open('uk_dcl_mrg.txt', 'r') as f:
It will work for all versions of python. But I recommend that you drop Python 2 unless you're tied to it and install Python 3 by default.
这篇关于pycharm 终端并运行给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!