2012-12-27 113 views
2

我只是刚开始进入Python的旅程。我想建立一个小程序来计算我在摩托车上进行气门间隙时的垫片尺寸。我将拥有一个具有目标许可的文件,并且我将询问用户输入当前的垫片尺寸和当前许可。该程序然后将吐出目标垫片尺寸。看起来很简单,我建立了一个电子数据表,做它,但我想学习Python,这似乎是一个很简单的项目......从txt文件中获取数据

总之,到目前为止,我有这样的:

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

+0

尝试'f.readlines()[3]'。 –

+0

相关错误在这里:http://stackoverflow.com/questions/13988421/reading-document-lines-to-the-user-python/13988466#13988466 –

回答

4

要阅读所有行:

lines = f.readlines() 

然后,打印线4:

print lines[4] 

注意的是Python开始指数为0,这样实际上是第五个行文件。

+0

嘿,我会尝试。大概只是采取该行的价值,而不是ptint它,我会做一些像'value = lines [4]'? 它是否必须是方括号? – Demonic

+0

+1。但是由于'readlines'在3.3中被弃用,所以值得学习“现代”版本'list(f)'而不是'f.readlines()'。但是,这确实需要更多的基础知识...... – abarnert

+0

正确,是的,你需要方括号。请注意,从'readline'(或'readlines')返回的行将包含换行符,因此您可能需要使用'value = lines [4] .strip()'。 – bogatron

-1

效率不高,但它应该告诉你它是如何工作的。基本上它会在它读取的每一行上保持一个运行计数器。如果该行是'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() 
+1

在Python中,几乎没有使用手动计数器的好理由。使用内建[枚举](http://docs.python.org/2/library/functions.html#enumerate)函数。 – kojiro

+0

哦,男人,柜台是我知道如何使用的少数事情之一! – Demonic

+0

我也是,我是一个固件人,所以Python不完全是我的“东西”,但我认为它可能对某人有用。 –

3
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 

的更多信息:

+0

这是一个很好的解决方案,因为它不会(尝试)先将所有行加载到内存中。 – poke

+0

@poke:当然,除非他想看第4行,然后是第176行,然后是第1行,然后是第73行... – abarnert

+0

@abarnert是的,对于这个问题没有好的解决方案,所以我猜这不是这是一个很好的解决方案。 – kojiro