Read lines from a text file into variables

2019-06-14 17:47发布

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.

2条回答
Anthone
2楼-- · 2019-06-14 18:08
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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-14 18:24
from string import ascii_uppercase
my_data = dict(zip(ascii_uppercase,open("some_file_to_read.txt"))
print my_data["A"]

this will store them in a dictionary with lettters as keys ... if you really want to cram it into variables(note that in general this is a TERRIBLE idea) you can do

globals().update(my_data)
print A
查看更多
登录 后发表回答