从txt fi中获取数据

2024-05-20 15:01:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是刚刚开始我的Python之旅。我想建立一个小程序,将计算垫片大小时,我做的阀门间隙对我的摩托车。我将有一个文件,将有目标间隙,我将查询用户输入当前垫片尺寸,和当前间隙。然后程序将吐出目标垫片大小。看起来很简单,我已经建立了一个电子表格,但我想学习python,这似乎是一个足够简单的项目。。。你知道吗

总之,到目前为止我有:

def print_target_exhaust(f):
    print f.read()

#current_file = open("clearances.txt")
print print_target_exhaust(open("clearances.txt"))

现在,我让它读取整个文件,但是如何使它只获取第4行的值。我在函数中尝试了print f.readline(4),但这似乎只是吐出了前四个字符。。。我做错什么了?你知道吗

我是新来的,请对我放松点! -d级


Tags: 文件用户程序txttarget目标尺寸open
3条回答

要阅读所有行:

lines = f.readlines()

然后,打印第4行:

print lines[4]

请注意,python中的索引从0开始,因此这实际上是文件中的第五行。你知道吗

with open('myfile') as myfile: # Use a with statement so you don't have to remember to close the file
    for line_number, data in enumerate(myfile): # Use enumerate to get line numbers starting with 0
        if line_number == 3:
            print(data)
            break # stop looping when you've found the line you want

更多信息:

不是很有效,但它应该告诉你它是如何工作的。基本上,它在每一行上都会有一个运行计数器。如果行是'4',那么它将打印出来。你知道吗

## Open the file with read only permit
f = open("clearances.txt", "r")
counter = 0
## Read the first line 
line = f.readline()

## If the file is not empty keep reading line one at a time
## till the file is empty
while line:
    counter = counter + 1
    if counter == 4
        print line
    line = f.readline()
f.close()

相关问题 更多 >