简体   繁体   English

python for loop修改文件中的每一行都会跳过第二行

[英]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. 我的for循环有问题,我已经在文档中阅读了为什么Python会通过修改迭代器而出现问题。 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() . 不要for line in filefile.readline()同时for line in file Your "missing" lines were in the variable line , which you didn't use for anything. 您的“缺失”行在变量line ,您什么都没用。

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在你的循环,只需使用当前行。 readline calls a next on your file iterator, so the current line in the loop is skipped. readline在文件迭代器上调用next ,因此跳过了循环中的当前行。

k = ast.literal_eval(line)

You have for line in f , which iterates through the lines in the file. for line in ffor line in f ,它在文件中的各行之间进行迭代。 Then in your very next line of code you have f.readline() which reads the next line in the file. 然后在下一行代码中,您将拥有f.readline()来读取文件中的下一行。 Thus, you are skipping every other line in the file. 因此,您将跳过文件中的所有其他行。

Just use line rather than f.readline() . 只需使用line而不是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. for语句从生成器f中读取一行并将其存储在变量line中 ,您将不再使用它。 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. 然后将k变量更改为line ,这样代码更易读。 :-) :-)

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

Your code has for line in f: and f.readline() . 您的代码for line in f:f.readline()for line in f: So you're reading two lines per loop. 因此,每个循环读取两行。

Use k = ast.literal_eval(line) . 使用k = ast.literal_eval(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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