Python-打开文件-readline-列表-转换为字符串

问题/问题详细信息

我有一个文件(blah.txt),其内容(列表)如下所示:

键1 = [ ‘A’, ‘B’, ‘C’, ‘d’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’ ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’,” Y’,’Z’,”]

在一个简单的python文件(称为CAT.py)中,我执行以下命令:

infile = open('blah.txt', 'r')
Key1 = infile.readline()
infile.close()
Key1 = Key1.rstrip('\n')
print(Key1)

Key1 = [‘A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’I’,’J’,’K’,’L’,’M’,’N’,’O’,’P’,’Q’,’R’,’S’,’T’,’U’,’V’,’W’,’X’,’Y’,’Z’,’ ‘]

  

print(''.join(Key1))

Key1 = [‘A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’I’,’J’,’K’,’L’,’M’,’N’,’O’,’P’,’Q’,’R’,’S’,’T’,’U’,’V’,’W’,’X’,’Y’,’Z’,’ ‘] <—- THIS IS WHAT I DO NOT WANT

  

然而….

如果在一个单独的简单的python文件(称为DOG.py)我执行的列表上运行以下命令:

键1 = [ ‘A’, ‘B’, ‘C’, ‘d’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’ ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’,” Y ‘ ‘Z’,’“]

打印(Key1)

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’, ‘ ‘]

  

打印( ”.加入(密钥1))

ABCDEFGHIJKLMNOPQRSTUVWXYZ <—- THIS IS WHAT I WANT

  

问题/问题

我最终要的,看起来像“ABCDEFGHIJKLMNOPQRSTUVWXYZ”的输出,但对我的生活我无法弄清楚如何在阅读列表的文件,然后将该列表转换为字符的单个字符串.有人可以告诉我我要去哪里哪里,还可以给我看一些代码来解决我的问题吗?

解决方法:

>>> infile = open('blah.txt', 'r')
>>> key1 = infile.readline()
>>> infile.close()
>>> key1 = "Key1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']"
>>> key1 = key1[key1.index('['):key1.index(']')+1]
>>> key1
"['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']"
>>> ''.join(eval(key1))
'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
上一篇:readLine的两种用法


下一篇:android-“ ImportError:没有名为readline的模块”运行“ repo init”