用于读取特定标头后的值的Python代码
假设我们有一个包含以下内容的文本文件:用于读取特定标头后的值的Python代码,python,python-3.x,file,Python,Python 3.x,File,假设我们有一个包含以下内容的文本文件: nope this one 24 25 nope again 我想经过一行,这一行,然后在这行上取值,所以24和25。 我已经在一些旧的Fortran代码中完成了这项工作,并且希望有一个Python3复制。以下是Fortran中的内容: subroutine read_until(unit, string, error) implicit none integer, parameter :: long_max=128
nope
this one
24 25
nope again
我想经过一行,这一行
,然后在这行上取值,所以24
和25
。
我已经在一些旧的Fortran代码中完成了这项工作,并且希望有一个Python3复制。以下是Fortran中的内容:
subroutine read_until(unit, string, error)
implicit none
integer, parameter :: long_max=128
integer, intent(in) :: unit
character(len=*), intent(in) :: string
character(len=long_max) :: control
logical, optional :: error
if (PRESENT(error)) error =.FALSE.
rewind(unit)
do while (.TRUE.)
read(unit,'(64A)',ERR=11,end=22) control
if (trim(adjust(control))==string) return
end do
return
11 write(*,*) ' Error when reading data file '
if (present(error)) error=.TRUE.
return
end subroutine read_until
open(11, file = data.txt, form = 'formatted', status = 'unknown')
call read_until(11, "this one")
read (11,*) first_val, second_val
因此,找到标题后面的行,然后开始读取行上由空格分隔的值。编写此命令的最简单方法是在行上循环:
with open('data.txt') as f:
for line in f:
if line.strip() == 'this one':
break
else:
raise ValueError('Header not found!')
…现在,文件中的下一行是我们要分析的行,因此:
line = next(f)
first_val, second_val = line.strip().split()
当然,在Python中,这些值不会自动转换为整数;您必须手动执行此操作:
first_val, second_val = int(first_val), int(second_val)
但就是这样,模运算处理那些ValueError
s(显式的,如果split
返回的字符串太多或太少,如果整数实际上不是整数,则引发的)和可能的IO错误。只需使用readline()读取一行,并进行while循环
def line_after():
with open("/file_path/filename", "r", encoding="utf-8") as f:
while true:
if "this one" in f.readline():
a, b = f.readline().split()
return int(a), int(b)
return None
Python中的开放文件句柄是迭代器。利用这个事实
with open("filename") as infile:
for line in infile: # Iterate through the file
if line.strip() == 'this one': # Find the marker
x, y = next(infile).split() # Go to the next line
break
int(x)
#24
int(y)
#25
通过将数据类型转换合并到循环体中,可以使代码更加紧凑:
x, y = map(int, next(infile).split())
堆栈溢出不是代码编写服务。试一试,当你遇到困难时,我们会很乐意帮助你。祝你好运噢,见鬼!我是否处于错误的通道中?尽管要采用的值数目未知,但此方法看起来如何?我是否可以将readline.split内容取出并在外部执行?
f.readline().split()
返回字符串列表。如果需要将其转换为int列表,可以执行以下操作:value=[int(string)for string in f.readline().split()]如果我在问题中添加您的答案的应用程序,可以吗?