[Tutor] Help!
Steven D'Aprano
steve at pearwood.info
Sun Jan 17 17:21:04 EST 2016
On Fri, Jan 15, 2016 at 11:33:24AM -0500, Chelsea G wrote:
> Hi,
[snip stuff which is, as far as I can see, irrelevant]
> 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?
This is how to change the file extension:
py> import os
py> filename = "weekly_20160102.csv"
py> newname = os.path.splitext(filename)[0] + ".txt"
py> print(newname)
weekly_20160102.txt
Once you have the new file name, ending with .txt, do you understand how
to open it and write to it? For example, you might do this:
with open(newname, "w") as f:
f.write("line 1\n")
f.write("second line\n")
f.write("last line\n")
When you exit the "with" block, the file will be automatically closed.
Remember to use \n (newline) at the end of each line.
--
Steve
More information about the Tutor
mailing list