0

I have taken input from Numbers.txt file and want to write output in out.txt file, can anyone guide what is going wrong.

import num2word_EN as s
text = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\Numbers.txt","r")
outfile = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\out.txt", "w")
for line in text:
    line = line.rstrip()
    num = int(line)
    print line
    x = s.to_card(num)
    print (x)
outfile.write("%s\n"%(line));
outfile.close()
text.close()
  • How does your file look like? – Willem Van Onsem Feb 28 '17 at 10:06
  • 5
    You need to indent `out_file.write()` otherwise you'll only write the last line – Chris_Rands Feb 28 '17 at 10:06
  • 2
    You didn't do `text.close()`, have a look at the example: http://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python which makes it easier to code bug free. Also I wouldn't import something within a for loop. – martijnn2008 Feb 28 '17 at 10:08
  • 1
    BTW, you should normally put `import` statements at the top of the script, not buried somewhere in the middle, and especially not inside a loop. It doesn't really matter that your `import` is in the loop because Python is smart enough to only import the module once, but it still looks messy. – PM 2Ring Feb 28 '17 at 10:09
  • 1
    Also, `x="";` is useless. And there's no need to terminate Python statements with a semicolon. – PM 2Ring Feb 28 '17 at 10:10
  • 2
    also, don't write files into python installation !!! – Jean-François Fabre Feb 28 '17 at 10:14
  • Still struggling with same no output can anyone frame the code. – Akshay Anand Feb 28 '17 at 10:15
  • please post your fixed code, since you followed advice in comments. and do you have permissions to write in `c:/python27` ? it's a bad idea whatever. – Jean-François Fabre Feb 28 '17 at 10:15
  • You have modified the code according to some suggestions but not all. The most important one "Indent the outfile.write("%s\n"%(line));" is not done. Others like the end semicolon is also not done. Please modify your code making all changes suggested by people. – Sembei Norimaki Feb 28 '17 at 10:48

1 Answers1

1

Here's an improved version of your code:

import num2word_EN as s

input_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\Numbers.txt'
output_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\out.txt'

with open(input_file, 'r') as fin 
    with open(output_file, 'w') as fout:
        for line in fin:
            num = int(line)
            print(line)
            x = s.to_card(num)
            print(x)
            # What's the data type of x? int? string?
            # This will write the original data and the processed data separated by tab.
            fout.write('%s\t%s\n' % (line.rstrip(), x));
Sembei Norimaki
  • 5,656
  • 2
  • 31
  • 62