0

I've been having trouble with the following piece of Python code. It's running without errors, but it isn't exactly giving me the expected output; no files at all are being written.

for l in h:                                                   
    r=l.rfind(",")+1
    s=l[r:-2]
    j=0
    while j<18:
        if s[j]==1:
            f=codecs.open("genre_"+str(j)+".csv","w","utf-8")
            f.write(l)
            f.close()
        j=j+1
  • h is a list of strings, typically something like 1,32,3.5,1112484819,000000000000101100\r\n
  • s is the end of a string in h , specifically the last number string
  • For each 1 in string s, the while loop writes the current string of h on a correspondingly indexed genre_[num].csv file

So, for instance, h[2] is the example string above, and the files genre_12.csv, genre_14.csv and genre_15.csv should be written with it. The thing is, after running the code, these genre files aren't even being created.

I've tried other variations of the code ('with codecs.open as f:') but fared no better. Am I missing something obvious?

2 Answers 2

0

The problem is that you set s to a string with s=l[r:-2] and then later check for an int with if s[j]==1:

Since the condition is never met there won't be any files written. Check for the string "1" instead and it will work:

for l in h:                                                  
    r=l.rfind(",")+1
    s=l[r:-2]
    j=0
    while j<18:
        if s[j]=="1":
            f=codecs.open("genre_"+str(j)+".csv","w","utf-8")
            f.write(l)
            f.close()
        j=j+1

`

1
  • Knew it had to be something basic. Thank you very much! Jun 5, 2016 at 20:51
0

You need to indent the code that is in our for-loop. Indentation is very important in python since there isn't the use of curly brackets or semi-colons. Hopefully this will solve the problem you are having!

:) Derek

for l in h:                                                  
    r=l.rfind(",")+1
    s=l[r:-2]
    j=0
while j<18:
    if s[j]==1:
        f=codecs.open("genre_"+str(j)+".csv","w","utf-8")
        f.write(l)
        f.close()
    j=j+1
2
  • Also, where you wrote j = j+ 1, you can instead write j += 1. This will save you save typing. :D Jun 5, 2016 at 20:27
  • Sorry about the identation; I mistyped. I corrected indentation in the question. Also; thanks for the increment tip Jun 5, 2016 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.