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()
-
\$\begingroup\$ See also: How do I read and write CSV files with Python? \$\endgroup\$Martin Thoma– Martin Thoma2017年03月18日 10:58:41 +00:00Commented Mar 18, 2017 at 10:58
3 Answers 3
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.
-
\$\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– Shawnic Hedgehog2015年02月19日 21:15:11 +00:00Commented Feb 19, 2015 at 21:15
-
1\$\begingroup\$ You're welcome. You can find a summary of the built-in python modules here. \$\endgroup\$Dries Van Rompaey– Dries Van Rompaey2015年02月19日 21:27:47 +00:00Commented Feb 19, 2015 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– Paul2015年02月20日 03:47:42 +00:00Commented Feb 20, 2015 at 3:47
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]
-
\$\begingroup\$ Is there any benefit to using
with
? \$\endgroup\$Shawnic Hedgehog– Shawnic Hedgehog2015年02月19日 19:57:29 +00:00Commented Feb 19, 2015 at 19:57 -
1\$\begingroup\$ @Saturick I updated the answer. \$\endgroup\$Caridorc– Caridorc2015年02月19日 20:27:33 +00:00Commented Feb 19, 2015 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– Shawnic Hedgehog2015年02月19日 21:20:12 +00:00Commented Feb 19, 2015 at 21:20
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.
-
1\$\begingroup\$ Could you explain why
with
should be used? \$\endgroup\$user34073– user340732015年02月19日 20:38:27 +00:00Commented Feb 19, 2015 at 20:38 -
\$\begingroup\$ This definitely makes the code more user friendly. Thank you for your input Andrey! \$\endgroup\$Shawnic Hedgehog– Shawnic Hedgehog2015年02月19日 21:18:37 +00:00Commented Feb 19, 2015 at 21:18