How to find the directory of opened file using python - TagMerge
3How to find the directory of opened file using pythonHow to find the directory of opened file using python

How to find the directory of opened file using python

Asked 1 years ago
0
3 answers

os.getcwd() returns the current directory of the python file.

Source: link

0

Reading and writing data to files using Python is pretty straightforward. To do this, you must first open files in the appropriate mode. Here’s an example of how to use Python’s “with open(…) as …” pattern to open a text file and read its contents:
with open('data.txt', 'r') as f:
    data = f.read()
open() takes a filename and a mode as its arguments. r opens the file in read only mode. To write data to a file, pass in w as an argument instead:
with open('data.txt', 'w') as f:
    data = 'some data to be written to the file'
    f.write(data)
Suppose your current working directory has a subdirectory called my_directory that has the following contents:
my_directory/
|
├── sub_dir/
|   ├── bar.py
|   └── foo.py
|
├── sub_dir_b/
|   └── file4.txt
|
├── sub_dir_c/
|   ├── config.py
|   └── file5.txt
|
├── file1.py
├── file2.csv
└── file3.txt
>>>
>>> import os
>>> entries = os.listdir('my_directory/')
>>>
>>> os.listdir('my_directory/')
['sub_dir_c', 'file1.py', 'sub_dir_b', 'file3.txt', 'file2.csv', 'sub_dir']

Source: link

0

Python’s os module provides a function to get the current working directory i.e.
os.getcwd()
For calling this function we need to import os module i.e.
import os
Python : How to Get the current working directory ? 1 Comment / Directories, Python / By Varun
'''
    Get Current working Directory
'''
currentDirectory = os.getcwd()
Python : How to Get the current working directory ? 1 Comment / Directories, Python / By Varun
/home/varun/python/tutorials
Python : How to Get the current working directory ? 1 Comment / Directories, Python / By Varun
'''
    Change the Current working Directory
'''
os.chdir('/home/varun')

Source: link

Recent Questions on python

    Programming Languages