导入文件并将整数转换为 int
Import file and convert integers into int
我 运行 遇到以下问题。
我导入一个看起来像 [[58, 59, 60]] 的文件。
打印它会得到 ['[[58, 59, 60]]']。
现在我只想将 58 59 60 添加到新列表中。问题是:
output gives ['[[58, 59, 60]]']
output[0] gives '[[58, 59, 60]]'
output[0][2] gives '5'
output[0][3] gives '8'.
有没有办法以只加载完整整数的方式导入文件?
with open('file', 'r') as fobj:
content = int(fobj.read())
您可以使用 json 在读取文件时将字符串转换为实际列表。
例如:
import json
def get_output(filename): # filename is name of text file
with open(filename) as fn:
output = json.loads(fn.read())
return output
如果文件 't.txt' 包含以下内容:[[58, 59, 60]]
,则 get_output('t.txt')
returns 列表 [[58, 59, 60]]
:
output = get_output('t.txt')
type(output) # ===> list
output[0] # ===> [58, 59, 60]
output[0][2] # ===> 60
我 运行 遇到以下问题。 我导入一个看起来像 [[58, 59, 60]] 的文件。 打印它会得到 ['[[58, 59, 60]]']。 现在我只想将 58 59 60 添加到新列表中。问题是:
output gives ['[[58, 59, 60]]']
output[0] gives '[[58, 59, 60]]'
output[0][2] gives '5'
output[0][3] gives '8'.
有没有办法以只加载完整整数的方式导入文件?
with open('file', 'r') as fobj:
content = int(fobj.read())
您可以使用 json 在读取文件时将字符串转换为实际列表。
例如:
import json
def get_output(filename): # filename is name of text file
with open(filename) as fn:
output = json.loads(fn.read())
return output
如果文件 't.txt' 包含以下内容:[[58, 59, 60]]
,则 get_output('t.txt')
returns 列表 [[58, 59, 60]]
:
output = get_output('t.txt')
type(output) # ===> list
output[0] # ===> [58, 59, 60]
output[0][2] # ===> 60