简体   繁体   中英

python for loop modify line in file skips every second line

i have a Problem with my for loop and i allready read in the Documentation why python have problems by modifing the iterator. Now I have following code:

f = open('test.txt', 'r')
g = open('test1.txt', 'w')


for line in f:
        k = ast.literal_eval(f.readline())
        p = Polygon(k)
        c = p.centroid
        print (c, file = g)
f.close()

Now it skips every second Line in the reading file and gives me the results just for half the input. I solved it with a regex by duplicating every line, but is there any better solution for this?

Don't use both for line in file and file.readline() . Your "missing" lines were in the variable line , which you didn't use for anything.

with open('test.txt') as f, open('test1.txt', 'w') as g:
    for line in f:
        k = ast.literal_eval(line)
        p = Polygon(k)
        c = p.centroid
        g.write('%s\n' % c)

You don't need to readline in your loop, just use the current line. readline calls a next on your file iterator, so the current line in the loop is skipped.

k = ast.literal_eval(line)

You have for line in f , which iterates through the lines in the file. Then in your very next line of code you have f.readline() which reads the next line in the file. Thus, you are skipping every other line in the file.

Just use line rather than f.readline() .

Your problem is right at the start:

for line in f:
    k = ast.literal_eval(f.readline())

The for statement reads a line from generator f and stores it in the variable line , which you never use again. Your first statement in the loop then explicitly reads the following line and works with that. Every time you go through the loop, you repeat the process.

Just change these to read

for k in f:

and see how that works. Then change the k variable to line , so the code is more readable. :-)

for line in f:
    print (Polygon(ast.literal_eval(line)).centroid, file = g)

Your code has for line in f: and f.readline() . So you're reading two lines per loop.

Use k = ast.literal_eval(line) .

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