将文本文件中的行读入变量 [英] Read lines from a text file into variables

查看:123
本文介绍了将文本文件中的行读入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中有两个不同的函数,一个输出写入一个txt文件(函数A),另一个读取它并将其用作输入(函数B)。

功能A很好(虽然我总是开放的建议,我可以改善)。
看起来像这样:

$ $ $ $ $ c $ def def createFile():
fileName = raw_input(Filename: )
fileNameExt = fileName +.txt#确保使用.txt扩展名
$ b $ line1 =1.1.1
line2 = int(input(Enter第2行:)
line3 = int(input(Enter line 3:)

file =(fileNameExt,w +)
file.write(%s \ n%s \%s%(line1,line2,line3))
file.close()

return

这似乎工作正常,并将创建一个文件,如

  1.1.1 
123
456

现在,函数B应该使用这个文件作为输入,这是我到目前为止得到的:

  def loadFile():
loadFileName = raw_input(Filename:)
loadFile = open(loadFileName,r)

line1 = loadFile.read(5)

这就是我卡住的地方,我知道如何使用这第一个5 ch字符,但我需要行2和3作为变量。

解决方案

  f = open( 'file.txt')
lines = f.readlines()
f.close()

是您想要的

其他选项:

$ $ $ $ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ lines.append(line)
f.close()

更多内容:



https ://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files


I have two different functions in my program, one writes an output to a txt file (function A) and the other one reads it and should use it as an input (function B).

Function A works just fine (although i'm always open to suggestions on how i could improve). It looks like this:

def createFile():
    fileName = raw_input("Filename: ")
    fileNameExt = fileName + ".txt" #to make sure a .txt extension is used

    line1 = "1.1.1"
    line2 = int(input("Enter line 2: ")
    line3 = int(input("Enter line 3: ")

    file = (fileNameExt, "w+")
    file.write("%s\n%s\n%s" % (line1, line2, line3))
    file.close()

    return

This appears to work fine and will create a file like

1.1.1
123
456

Now, function B should use that file as an input. This is how far i've gotten so far:

def loadFile():
    loadFileName = raw_input("Filename: ")
    loadFile = open(loadFileName, "r")

    line1 = loadFile.read(5)

That's where i'm stuck, i know how to use this first 5 characters but i need line 2 and 3 as variables too.

解决方案

f = open('file.txt')
lines = f.readlines()
f.close()

lines is what you want

Other option:

f = open( "file.txt", "r" )
lines = []
for line in f:
    lines.append(line)
f.close()

More read:

https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

这篇关于将文本文件中的行读入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆