简体   繁体   English

Python中a.txt文件如何打印到下一行

[英]How to print to the next line in a .txt file in Python

'''def get_us_value(fp):
    '''Insert docstring here.'''
    print()
    print(fp.readline())
    for x in fp:
        for y in x.split():
            if y == 'States':'''

I would like to print the next line after states in order to get the number associated with United States but I am currently stuck on how to print the next line after states.我想在州之后打印下一行以获得与美国相关的数字,但我目前停留在如何在州之后打印下一行。 This is the.txt file这是.txt文件

United
States
91.9

You can use \n.你可以使用\n。

For example: if you do print(“foo \nbar”) foo is line one, bar is line two.例如:如果你执行 print(“foo \nbar”) foo 是第一行,bar 是第二行。

Look at this, it can be helpful: https://www.google.co.uk/amp/s/cmdl.netips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/amp/看看这个,它会有所帮助: https://www.google.co.uk/amp/s/cmdl.netips.com/2012/09/three-ways-to-write-text-to-a-file -in-python/放大器/

You can use the next function on the file object to obtain the next line:您可以使用文件 object 上的next function 来获取下一行:

for x in fp:
    if 'States' in x.split():
        print(next(fp), end='')

You may not pick this solution as I don't know whether you can use regex or not but you can use regex to get the matching result.你可能不会选择这个解决方案,因为我不知道你是否可以使用正则表达式,但你可以使用正则表达式来获得匹配结果。 I don't know what the use case actually is but assuming you only have those lines in a text file, the regex States\n(.*) should match the whole line after the keyword States .我不知道实际用例是什么,但假设文本文件中只有这些行,则正则表达式States\n(.*)应该匹配关键字States之后的整行。

import re

print(re.findall(r"States\n(.*)", fp.read())[0])

Output: Output:

91.9

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

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