Search code examples
pythonpython-3.xfilepython-os

How to get the current working directory with os library and write a .txt file on it?


I want to find the current working directory (cwd) with os library and write .txt file on it.

Something like this:

import os

data=["somedatahere"]
#get_the_current_directory
#if this_is_the_current_directory:
  new_file=open("a_data.txt", "a")
  new_file.write(data)
  new_file.close()

Solution

  • It can be done using the os library, but the new pathlib is more convenient if you are using Python 3.4 or later:

    import pathlib
    data_filename = pathlib.Path(__file__).with_name('a_data.txt')
    with open(data_filename, 'a') as file_handle:
        file_handle.write('Hello, world\n')
    

    Basically, the with_name function said, "same dir with the script, but with this name".