0

I have a problem with my code - it doesnt enter the loop "for line in f2". This code is supposed to compare two files and if string in column 0 from one file matches the stiring in column 1 in second file write it down to the file.

Im a beginner with Python, so I have no idea what's wrong. I tried debugging but it didnt provide any help. Does anyone know what am I doing wrong?

f1=open("D:\\bowtie2\\posortowane_cale_test.csv","w")
with open("D:\\bowtie2\\dobazy228k_test.csv") as f:
    for yy in f:
        y=yy.split(";")
        #print(y)
        #sp1=y[1]
    with open ("D:\\bowtie2\\zliczone_test.csv") as f2:
        for xx in f2:
            xx=xx[0:len(xx)-1]
            x=xx.split(";")
        for line in f2:
            sp1=y[0]
            sp2=x[1]
            print("bb")
            if sp1==sp2:
                print("aaa")
                f1.write(x[1]+";"+y[0]+"\n")#";"+x[1]+";"+x[2]+";"+x[3]+";"+x[6]+";"+x[7]+";"+x[8]+";"+sp1+"/"+sp2+"\n")
    f2.close()
f.close()
f1.close()
Ania
  • 1
  • 1
    Possible duplicate of [Read multiple times lines of the same file Python](https://stackoverflow.com/questions/26294912/read-multiple-times-lines-of-the-same-file-python) –  Aug 14 '19 at 11:55
  • Hi, welcome to stack overflow, I hope you have fun so far. Please always conside this https://stackoverflow.com/help/how-to-ask when asking a question, it will help for your answer – PV8 Aug 14 '19 at 11:56
  • 2
    But I can't understand why you want two loops there. The values from the first loop are simply thrown away. Why not carry straight on inside the same loop? – Daniel Roseman Aug 14 '19 at 11:57

2 Answers2

0

Use f2.seek(0) to jump to the start of the file again after the first complete read. Even though you are not using the read method directly, the read pointer still moves to the position after the last read byte/character.

Valdrinium
  • 1,398
  • 1
  • 13
  • 28
0

Answer proposal

It seems that your indentations level are off because you first iterate over f and the variable y gets overridden. Only then, you attempt compare. Also, for xx in f2: is equivalent to for line in f2:. If I interpret your code correctly, removing for line in f2: and intending everything including and after with open ("D:\\bowtie2\\zliczone_test.csv") as f2: fixes the code.

Side Note

On a side note, you can use an r before the string

"D:\bowtie2\posortowane_cale_test.csv"

to interpret the following string as a raw string, meaning that **** inside the string is not considered as an escape character anymore and you can copy-paste file-paths:

r"D:\bowtie2\posortowane_cale_test.csv"

cptnJ
  • 230
  • 2
  • 8