Pergunta

I have the following code:

# Initialisations

filename='/home/Admin/Desktop/Ncapa/i_capa.txt'
f = open(filename, 'r') 

ty = "r"
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()

d = float(f.readline())
D = float(f.readline())
BB = float(f.readline())
vrR = float(f.readline())
P = float(f.readline())
f0 = float(f.readline())
f1 = float(f.readline())

f.close()
os.system('ls -lt > ./capacite.x')
filename2 = '/home/Admin/Desktop/Ncapa/o_capa.txt'
f = open(filename2, 'r')

f.readline()
f.readline()
f.readline()
f.readline()
c0 = float(f.readline())

f.close()   

My first question (as you may have already guessed, is a very simple one), is there a way of reducing the f.readline block to something simple? I always get confused how to read a text file and then take values from a list to assign to variables. So I ended up doing it this way as I like the way it works but don't like the look of the code as a whole. I haven't used f.readlines() as I get confused how to get certain values from the list you get using it.

My second question corresponding to the line:

os.system('ls -lt > ./capacite.x')

Is there a way of executing an .x file in Python in Linux? This line doesn't appear to cause any problems but I know it doesn't work either as this file produces the o_capa.txt file which up until this point I have had to fill in by hand to test the rest of my programme.

Any help would be greatly appreciated =)

Foi útil?

Solução

If you know the name and line for each variable, create a dictionary:

position = {12: 'd',
            13: 'D', ... }
data = {}
with open(filename, 'r') as f:
    for i, line in enumerate(f):
        if i in position:
            data[position[i]] = float(line.strip())

Then use the data dictionary as if it were variables, such as data['d'].

Outras dicas

why don't you use

f.readlines()

You can run the readline in a loop something similar to the below

try:
    [fin.xreadlines().next() for i in xrange(0,<some_limit>)]
    d = float(fin.xreadlines().next())
except StopIteration:
    None
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top