Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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()
share|improve this question

3 Answers 3

up vote 3 down vote accepted

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.

share|improve this answer
    
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! –  Saturisk 10 hours ago
1  
You're welcome. You can find a summary of the built-in python modules here. –  Dries Van Rompaey 10 hours ago
    
@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. –  Paul 3 hours ago

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]
share|improve this answer

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

    
Is there any benefit to using with? –  Saturisk 11 hours ago
1  
@Saturick I updated the answer. –  Caridorc 11 hours ago
    
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. –  Saturisk 10 hours ago

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.

share|improve this answer
1  
Could you explain why with should be used? –  Hosch250 10 hours ago
    
This definitely makes the code more user friendly. Thank you for your input Andrey! –  Saturisk 10 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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