[Tutor] Help!

Peter Otten __peter__ at web.de
Fri Jan 15 12:50:57 EST 2016


Chelsea G wrote:

> What I am having issues with is the def txt_output that is where I am
> trying to take the .csv off and add the .txt but keep the filename the
> same. For example, having a filename "weekly_20160102.csv" and then create
> a txt filename with "weekly_20160102.txt" and have all the counts and
> products in the text file. Is there any way to do this?

The best approach is to solve small subproblems in a simple experimental 
file or in the interactive interpreter before you integrate the solution as 
a function that you have tested and found to be working as intended.

If you look around the os.path module you'll find the splitext() function 
which works like this:

>>> import os.path
>>> os.path.splitext("/foo/bar/baz.ext")
('/foo/bar/baz', '.ext')

To change the extension you can do

>>> os.path.splitext("/foo/bar/my.csv")[0] + ".txt"
'/foo/bar/my.txt'

Now put it into a function:

>>> def change_ext(filename, newext):
...     return os.path.splitext(filename) + newext
... 

Let's test:

>>> change_ext("/foo/bar/my.one", ".two")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in change_ext
TypeError: can only concatenate tuple (not "str") to tuple

Oops, I made an error. Do you spot it? Let's fix it:

>>> def change_ext(filename, newext):
...     return os.path.splitext(filename)[0] + newext
... 
>>> change_ext("/foo/bar/my.one", ".two")
'/foo/bar/my.two'

Ok, this seems to work. You can do more tests (e.g. how will multiple 
extensions like "archive.tar.gz" or missing extensions like "somescript" be 
handled) and once it works as intended integrate it into your script.



More information about the Tutor mailing list