Tony Cardinal
Tony Cardinal

Reputation: 25

How do you write a new text file (and also an excel file) to your default directory or a specific directory using python?

I used the code below from Starting Out WIth Python 5th edition and I do not see a text file in the directory I specified. I used Jupyter notebook to run the code:

def main():
       # Open a file named philosophers.txt.
       outfile = open(r'C:\Users\ME\philosophers.txt', 'w')
 
       # Write the names of three philosphers
       # to the file.
       outfile.write('John Locke\n')
       outfile.write('David Hume\n')
       outfile.write('Edmund Burke\n')

       # Close the file.
       outfile.close()

  # Call the main function.
if __name__ == '_ _main_ _':
          main()

I ran the code included in this post and all I see is a file called IPNYB in the directory. I suppose it is a Jupyter notebook file. I was expecting a plain old text file named philosophers.txt. Then I went into the directory I chose, created a text filed, named it "philosophers.txt" then I ran the python code and the text file was till empty and did not include the text I specified in the outfile.write methods.

Upvotes: 0

Views: 34

Answers (1)

BishwashK
BishwashK

Reputation: 171

Welcome to SO! You should use os module to avoid trouble in cross-platform and do this:

import os
filename = "philosophers.txt"

x = os.path.join("C:/Users/ME", "filename")

with open(x, "w") as outfile:
    outfile.write("John Locke\n")
    outfile.write("David Hume\n")
    outfile.write("Edmund Burke\n")
    outfile.close

Hope this helps!

Upvotes: 1

Related Questions