7
\$\begingroup\$

At my job, often I have to manually convert *.csv Files structured like:

number,number\n
number,number\n
number,number\n
...

To a regular *.txt file with the structure:

#1
double filename(number of columns, number of columns) 
 number number
 number number
 number number
 ...

This file is an input to another program, and rather than spending the time to copy and paste the excel sheet into notepad and crop out all the commas and make sure there are spaces and such I decided to write a python script that would do it for me.

Now, to be fair, I am new to Python, and this script works perfectly (first try), I would just like some feedback on my methods, or ways to improve my quality of code.

# A simple program to create a formatted text file from a *.csv file.

csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

try:
    my_input_file = open(csv_file, "r")
except IOError as e:
    print("I/O error({0}): {1}".format(e.errno, e.strerror))

if not my_input_file.closed:
    text_list = [];
    for line in my_input_file.readlines():
        line = line.split(",", 2)
        text_list.append(" ".join(line))
    my_input_file.close()

try:
    my_output_file = open(txt_file, "w")
except IOError as e:
    print("I/O error({0}): {1}".format(e.errno, e.strerror))

if not my_output_file.closed:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')
    my_output_file.close()
\$\endgroup\$
3
\$\begingroup\$

As others have already mentioned, using with to handle your input and output files would be a bit cleaner. with will handle the opening and closing of your file for you as explained here. It's also a bit shorter. In addition, you could handle the reading of your csv file with the python csv module. This will increase readability and could make your code more reusable.

\$\endgroup\$
  • \$\begingroup\$ I wasn't aware that python had a built-in module.. I thought they were only third-party for some reason. Thank you for pointing that out! \$\endgroup\$ – Shawnic Hedgehog Feb 19 '15 at 21:15
  • 1
    \$\begingroup\$ You're welcome. You can find a summary of the built-in python modules here. \$\endgroup\$ – Dries Van Rompaey Feb 19 '15 at 21:27
  • 1
    \$\begingroup\$ @saturisk it is important to use a csv module that has coverage of some of csv's nastier edge cases e.g., quotes, commas, escapes, and other nastiness that will break simple decoding schemes like splitting on comma. \$\endgroup\$ – Paul Feb 20 '15 at 3:47
3
\$\begingroup\$

Use with when dealing with files.

There are great benefits discussed in the docs. Summarizing it handles closing and exceptions automatically. It makes it possible to write shorter code: look Andrey's answer for a rewrite.

Miscellaneous

  • Drop my from the start of your variables' names.
  • Learn list comprehension because it is extremely powerful, here I give you an example:

:

with open(csv_file) as input_file:
    lines = [line.split(",", 2) for line in input_file.readlines()]
    text_list = [" ".join(line) for line in lines]
\$\endgroup\$
  • \$\begingroup\$ Is there any benefit to using with? \$\endgroup\$ – Shawnic Hedgehog Feb 19 '15 at 19:57
  • 1
    \$\begingroup\$ @Saturick I updated the answer. \$\endgroup\$ – Caridorc Feb 19 '15 at 20:27
  • \$\begingroup\$ Is removing the use of "my" as a prefix just a user preference? I figure it makes understanding the variables a little easier, or so I have been taught. \$\endgroup\$ – Shawnic Hedgehog Feb 19 '15 at 21:20
2
\$\begingroup\$

The same using with:

csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

text_list = []

with open(csv_file, "r") as my_input_file:
    for line in my_input_file:
        line = line.split(",", 2)
        text_list.append(" ".join(line))

with open(txt_file, "w") as my_output_file:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')

In this case with statement guarantees that opened file will be closed as soon as you leave with code block even in case of failure.

More detailed description you can find here.

\$\endgroup\$
  • 1
    \$\begingroup\$ Could you explain why with should be used? \$\endgroup\$ – Hosch250 Feb 19 '15 at 20:38
  • \$\begingroup\$ This definitely makes the code more user friendly. Thank you for your input Andrey! \$\endgroup\$ – Shawnic Hedgehog Feb 19 '15 at 21:18

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.