Note that there are some explanatory texts on larger screens.

plurals
  1. POEncoding issue when writing to text file, with Python
    text
    copied!<p>I'm writing a program to 'manually' arrange a csv file to be proper JSON syntax, using a short Python script. From the input file I use <code>readlines()</code> to format the file as a list of rows, which I manipulate and concenate into a single string, which is then outputted into a separate .txt file. The output, however, contains gibberish instead of Hebrew characters that were present in the input file, and the output is double-spaced, horizontally (a whitespace character is added in between each character). As far as I can understand, the problem has to do with the encoding, but I haven't been able to figure out what. When I detect the encoding of the input and output files (using <code>.encoding</code> attribute), they both return <code>None</code>, which means they use the system default. Technical details: Python 2.7, Windows 7. </p> <p>While there are a number of questions out there on this topic, I didn't find a direct answer to my problem. Detecting the system defaults won't help me in this case, because I need the program to be portable.</p> <p>Here's the code:</p> <pre><code>def txt_to_JSON(csv_list): ...some manipulation of the list... return JSON_string file_name = "input_file.txt" my_file = open(file_name) # make each line of input file a value in a list lines = my_file.readlines() # break up each line into a list such that each 'column' is a value in that list for i in range(0,len(lines)): lines[i] = lines[i].split("\t") J_string = txt_to_JSON(lines) json_file = open("output_file.txt", "w+") json_file.write(jstring) json_file.close() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload