Python从文件中读取字符串并将其分割为值

时间:2021-01-15 20:15:03

I have a file in the format below:

我有一个文件格式如下:

995957,16833579
995959,16777241
995960,16829368
995961,50431654

I want to read in each line but split the values into the appropriate values. For example the first line would be split into:

我想在每行中读取,但将值分割为适当的值。例如,第一行将被分为:

x = 995957
y = 16833579

Since its a string when you read it in and I want to convert them to an int and split them, how exactly would I go about doing this? Any help would be appreciated.

因为它是一个字符串,当你读它的时候,我想把它们转换成一个int类型并将它们分开,我该怎么做呢?如有任何帮助,我们将不胜感激。

Thanks!

谢谢!

4 个解决方案

#1


15  

Something like this - for each line read into string variable a:

类似这样的东西-对于每一行读成字符串变量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

Now you can do what is necessary with x and y as assigned, which are integers.

现在你可以用x和y来做必要的事情了,这是整数。

#2


16  

I would do something like:

我会这样做:

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."

The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.

在http://docs.python.org/tutorial/inputoutput.html中推荐使用with open,因为它确保即使在处理过程中引发异常,也能正确关闭文件。

#3


10  

Use open(file, mode) for files. The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.

对文件使用open(file, mode)。该模式是“r”的变体,“w”是“写”,可能还会“b”(如“rb”)附加到打开二进制文件。请参阅下面的链接。

Use open with readline() or readlines(). The former will return a line at a time, while the latter returns a list of the lines.

与readline()或readlines()一起使用open。前者每次返回一行,而后者返回一行的列表。

Use split(delimiter) to split on the comma.

在逗号上使用split(分隔符)。

Lastly, you need to cast each item to an integer: int(foo). You'll probably want to surround your cast with a try block followed by except ValueError as in the link below.

最后,需要将每个项转换为整数:int(foo)。您可能想要使用try块包围您的cast,后面跟着except ValueError,如下面的链接所示。

You can also use 'multiple assignment' to assign a and b at once:

你也可以同时使用“多重分配”来分配a和b:

>>>a, b = map(int, "2342342,2234234".split(","))  
>>>print a  
2342342
>>>type(a)  
<type 'int'>

python io docs

python io文档

python casting

python铸造

#4


1  

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

#1


15  

Something like this - for each line read into string variable a:

类似这样的东西-对于每一行读成字符串变量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

Now you can do what is necessary with x and y as assigned, which are integers.

现在你可以用x和y来做必要的事情了,这是整数。

#2


16  

I would do something like:

我会这样做:

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."

The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.

在http://docs.python.org/tutorial/inputoutput.html中推荐使用with open,因为它确保即使在处理过程中引发异常,也能正确关闭文件。

#3


10  

Use open(file, mode) for files. The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.

对文件使用open(file, mode)。该模式是“r”的变体,“w”是“写”,可能还会“b”(如“rb”)附加到打开二进制文件。请参阅下面的链接。

Use open with readline() or readlines(). The former will return a line at a time, while the latter returns a list of the lines.

与readline()或readlines()一起使用open。前者每次返回一行,而后者返回一行的列表。

Use split(delimiter) to split on the comma.

在逗号上使用split(分隔符)。

Lastly, you need to cast each item to an integer: int(foo). You'll probably want to surround your cast with a try block followed by except ValueError as in the link below.

最后,需要将每个项转换为整数:int(foo)。您可能想要使用try块包围您的cast,后面跟着except ValueError,如下面的链接所示。

You can also use 'multiple assignment' to assign a and b at once:

你也可以同时使用“多重分配”来分配a和b:

>>>a, b = map(int, "2342342,2234234".split(","))  
>>>print a  
2342342
>>>type(a)  
<type 'int'>

python io docs

python io文档

python casting

python铸造

#4


1  

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]