简体   繁体   中英

Multiply 10th index for every line by 2

I'm very new to programming so I thought I'd start out with what seems like a simple task. I'm getting stuck however, so I'm hoping for some of your feedback.

What am I trying to do:

I have a file that has 32 lines of string.

I would like to multiply the 10th index of every string by 2.

Then I want to replace the 10th index of every string by the newly calculated number.

Then I would like to save to file to a new directory.

What have I managed so far (pretty pityful):

I was able to extract the 10th number on my string and multiply it by 2. However, I can't seem to properly join the multiplied number into the pre-existing strings.

I also don't know how to then write the file off to a new directory.

Example of one of the 32 strings:

FLBR id 'Knoop_debiet2' sc 0 lt 0 dc lt 0 0.05 0 flbr

My code so far:

f = open('C:\\Sobek215\\PythonWd.lit\\1\\LATERAL.DAT', 'r')
linelist = f.readlines()
print(linelist)
f.close

for line in linelist:
    line = line.split(' ')
    flow = float(line[10])
    fl_2Q = flow*2
    print(fl_2Q)
    line[10] = str(fl_2Q)
    ListToString = ' '.join(str(linelist) for line[10] in line)
    print(linelist)

I would do something like the following (quasi-pseudo-code):

f = open('dir/file.txt', 'r')
l = [" ".join([line.split()[c] if c != 10 else str(float(line.split()[c])*2) for c in range(len(line.split()))]) for line in f.read().splitlines()]
with open('newdir/file.txt', 'w') as n:
    n.write("\n".join(l))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM