Ras*_*lly 4 python arrays io int python-2.x
我有一个文本文件,看起来像:
-45 64 -41 -51
95 96 -74 -74 56 41
41 64 -62 75
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其转换为int数组.
到目前为止,我尝试将它变成一个大字符串然后转换它,但当我尝试摆脱白色空格时,输出仍然看起来像txt文件.
file = open("dir", "r")
line = file.read()
line.strip()
line.replace(" ","")
print line
line.close()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我可以直接从文件中读取它到一个int数组吗?
你几乎就在那里 - 你需要用str.split而不是str.strip和str.replace.然后map结果为整数.您还可以使用将自动关闭文件(而不是a line)的上下文管理器.
with open('dir') as f:
content = file.read()
array = content.split()
numbers = map(int, array)
print array
Run Code Online (Sandbox Code Playgroud)