Pau*_*aul 11 python split file
我有一个以下格式的文件:
995957,16833579
995959,16777241
995960,16829368
995961,50431654
Run Code Online (Sandbox Code Playgroud)
我想读取每一行,但将值拆分为适当的值.例如,第一行将分为:
x = 995957
y = 16833579
Run Code Online (Sandbox Code Playgroud)
由于它是一个字符串,当你读入它并且我想将它们转换为int并拆分它们时,我究竟会怎么做呢?任何帮助,将不胜感激.
谢谢!
icy*_*com 16
这样的东西 - 每行读入字符串变量a:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
Run Code Online (Sandbox Code Playgroud)
现在,您可以执行必要的x和y已分配的整数.
Ken*_*Ken 16
我会做的事情如下:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
Run Code Online (Sandbox Code Playgroud)
在http://docs.python.org/tutorial/inputoutput.html中建议使用open,因为它确保即使在处理过程中引发异常也能正确关闭文件.
jdp*_*c06 10
使用open(file, mode)的文件.该模式是'r'用于读取的变体,'w'用于写入,并且可能'b'附加(例如,'rb')以打开二进制文件.请参阅以下链接.
open与readline()或一起使用readlines().前者将一次返回一行,而后者返回行列表.
使用split(delimiter)分裂的逗号.
最后,您需要将每个项目转换为整数:int(foo).你可能想要用try块包围你的演员,然后except ValueError在下面的链接中.
您还可以使用"多次分配"一次分配a和b:
>>>a, b = map(int, "2342342,2234234".split(","))
>>>print a
2342342
>>>type(a)
<type 'int'>
Run Code Online (Sandbox Code Playgroud)