简体   繁体   English

Python:从文件中读取数据

[英]Python: Read in Data from File

I have to read data from a text file from the command line. 我必须从命令行从文本文件读取数据。 It is not too difficult to read in each line, but I need a way to separate each part of the line. 在每一行中阅读都不太困难,但是我需要一种方法来分隔行的每个部分。

The file contains the following in order for several hundred lines: 该文件包含以下几百行内容:
String (Sometimes more than 1 word) 字符串(有时超过1个字)
Integer 整数
String (Sometimes more than 1 word) 字符串(有时超过1个字)
Integer 整数

So for example the input could have: 因此,例如,输入可能具有:

Hello 5 Sample String 10

The current implementation I have for reading in each line is as follows... how can I modify it to separate it into what I want? 我在每一行中都需要阅读的当前实现如下...如何修改它以将其分成我想要的? I have tried splitting the line, but I always end up getting only one character of the first string this way with no integers or any part of the second string. 我尝试过分割线,但是我总是最终只能以这种方式获得第一个字符串的一个字符,而没有整数或第二个字符串的任何部分。

with open(sys.argv[1],"r") as f:
    for line in f:
        print(line)

The desired output would be: 所需的输出将是:

Hello
5
Sample String
10

and so on for each line in the file. 对文件中的每一行等等。 There could be thousands of lines in the file. 文件中可能有数千行。 I just need to separate each part so I can work with them separately. 我只需要分开每个部分,以便可以分别使用它们。

The program can't magically split lines the way you want. 该程序无法以所需的方式神奇地分割行。 You will need to read in one line at a time and parse it yourself based on the format. 您将需要一次阅读一行,然后根据格式自行解析。

Since there are two integers and an indeterminate number of (what I assume are) space-delimited words, you may be able to use a regular expression to find the integers then use them as delimiters to split up the line. 由于有两个整数,并且有不确定数量的(我假设是)以空格分隔的单词,因此您可以使用正则表达式查找整数,然后将它们用作分隔符以分隔行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM