我的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
发布于 2012-12-28 05:46:00
要读取所有行:
lines = f.readlines()
然后,打印第4行:
print lines[4]
请注意,python中的索引从0开始,因此这实际上是文件中的第五行。
发布于 2012-12-28 05:49:30
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
更多信息:
发布于 2012-12-28 05:49:11
效率不是很高,但它应该会向您展示它是如何工作的。基本上,它将在它读取的每一行上保持一个运行计数器。如果行是'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()
https://stackoverflow.com/questions/14061689
复制相似问题