简体   繁体   English

逐行将txt文件读取到python

[英]Reading txt file to python line by line

I have txt-file in the form: 我有以下形式的txt文件:

1 2 3 4 5 6
7 8 9 10 11 
12 13 14 15 

So for me, the lines are obviously seperated by beginning a new line. 因此,对我来说,开始新的一行显然会将这些行分隔开。

Now I want to read these lines and store every line to a new variable. 现在,我想阅读这些行并将每行存储到一个新变量。 I tried: 我试过了:

with open('centroids_ET.txt') as f:
      CD_cent=f.readlines()  

and also: 并且:

with open('centroids_ET.txt') as f:
     CD_cent = []
     for line in f:
           CD_cent.append(line)

But It always stores all other lines in this variable as well. 但是它也总是将所有其他行也存储在此变量中。 I checked with print(len(line)) if it recognizes all lines, but it takes all as one line as it seems. 我检查了print(len(line))是否可以识别所有行,但看起来却像是一行一样。

So my question, how can I fix this? 所以我的问题是,我该如何解决? Is it maybe an issue of the layout of the txt-file? 可能是txt文件的布局问题吗? Do I need to seperate the lines in the txt-file in a special way? 我是否需要以特殊方式分隔txt文件中的行? Thanks in advance! 提前致谢!

Now, having everything in a list should be everything you need from a doing what you need point of view - there is no real advantage to having everything in a separate variable unless it improves your code legibility/quality. 现在,从所需的角度来看,将所有内容都包含在列表中应该是您需要的所有内容-将所有内容都放在单独的变量中并没有真正的优势,除非它可以提高代码的可读性/质量。

(You can always access the elements in CD_cent via indexes start at 0. e;g to get the 2'nd element you would use CD_cent[1] ) (您始终可以通过从0开始的索引访问CD_cent的元素。例如,要使用CD_cent[1]获得第二个元素)

However, if you knew the number of lines in your file you could always do this 但是,如果您知道文件中的行数,则可以始终执行此操作

with open("My_File") as f:
    #We know there are 3 lines
    #You may want to rstrip to remove newline characters
    line1 = f.readline()
    line2 = f.readline()
    line3 = f.readline()

Now if you don't, and I stress that this seems useless, you could always do this: 现在,如果您不这样做,并且我强调这似乎没有用,则可以始终这样做:

with open("MY_FILE") as f:
    #NUM_LINES can change
    #You may want to rstrip to remove newline characters
    for lineNum in range(1,NUM_LINES+1):
        exec("line"+str(lineNum)+" = f.readline()")

Now this would produce variables line1 , line2 and line3 if NUM_LINES was 3, line1 , line2 ,..., line5 if NUM_LINES was 5 ect. 现在,这将产生变数line1line2line3 ,如果NUM_LINES为3, line1line2 ,..., line5如果NUM_LINES为5等。

Please note that this code is python 3.4, which is what I believe you are using 请注意,这段代码是python 3.4,我相信您正在使用

Edit: Even easier and shorter https://stackoverflow.com/a/3277516/2019601 编辑:更容易和更短https://stackoverflow.com/a/3277516/2019601

input.txt: input.txt中:

1 2 3 4 5 6
7 8 9 10 11 
12 13 14 15 

test.py: test.py:

with open("input.txt") as fh:
  content = fh.read()

lines = []
for line in content.split("\n"):
  lines.append(line)

print(lines) 

Output: (Three lines -> Three elements in the array) 输出:(三行->数组中的三个元素)

['1 2 3 4 5 6', '7 8 9 10 11 ', '12 13 14 15 ']

try this: 尝试这个:

    def main():
    fname = "PythonQuestion.txt"
    with open(fname) as f:
        content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print content

if __name__ == '__main__':
    main()

This will result in an array with this content: 这将导致具有以下内容的数组:

['1 2 3 4 5 6', '7 8 9 10 11', '12 13 14 15']

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

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