About Python and os operations

(1) Premise

Create a directory test on your desktop and create test.py and test.txt in the directory. test.txt is described as "test completed". Create directory text2 in the directory and create test2.txt. test2.txt describes "Test 2 completed".

test
├test.py
├test.txt (describe "test completed")
└test2
 └test2.txt (describe "Test 2 completed")

(2)pwd Enter the current directory and pwd in the terminal as follows

/Users/*******/desktop/test

(3) os.getcwd () and \ __ file__

Get the absolute path of the current directory with os.getcwd () and get the relative path from within the current directory with \ __ file__.

import os

print(os.getcwd())
print(__file__)

The execution result is as follows.

/Users/*******/Desktop/test
file_test.py

(5)os.path.abspath() You can get the relative path from the current directory with \ __ file__, but you can convert it to an absolute path with os.path.abspath (). The directory can also be obtained with an absolute path.

import os

print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__)))

The execution result is as follows.

/Users/*******/Desktop/test/file_test.py
/Users/*******/Desktop/test

(6)os.path.join os.path.join can combine two character strings given in the argument into one path. First, read test.txt in the directory test.

with open('test.txt',encoding='utf-8') as f:
    print(f.read())

Then, it becomes as follows.

Test completed

Next, read test2.txt in the directory test2.

with open('test2/test2.txt',encoding='utf-8') as f:
    print(f.read())

Then, it becomes as follows.

Test 2 completed

Next, use os.path.join to read test2 by combining the absolute path to the current directory and the relative path to test2.txt.

import os

target = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test2/test2.txt')
with open(target,encoding='utf-8') as f:
    print(f.read())

Then, it becomes as follows.

Test 2 completed

(7)chdir chdir Used as [destination path]. Used when moving the current directory on the terminal. First, create a destination path.

import os
target2 = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test2')

Move the current directory via the set destination path.

os.chdir(target2)

Just in case, check the current directory and check if it has moved.

print(os.getcwd())

From test, I was able to confirm that the current directory could be moved to test2.

/Users/*********/Desktop/test/test2

When I read test2.txt directly (

with open('test2.txt',encoding='utf-8')as f:
    print(f.read())

It is output properly as follows. (If the current directory is test, with open ('test2.txt', encoding ='utf-8') is replaced with with open ('test2.test2.txt', encoding ='utf-8') There is a need to.)

Test 2 completed

(8) Summary

.py:test.py


import os

print(os.getcwd())
print(__file__)
print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__)))

print('------------------------------------')

with open('test.txt',encoding='utf-8') as f:
    print(f.read())
with open('test2/test2.txt',encoding='utf-8') as f:
    print(f.read())
target = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test2/test2.txt')
with open(target,encoding='utf-8') as f:
    print(f.read())

print('------------------------------------')

target2 = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test2')
os.chdir(target2)
print(os.getcwd())
with open('test2.txt',encoding='utf-8')as f:
    print(f.read())

Referenced site

Get the location (path) of the file running in Python file

Recommended Posts

About Python and os operations
About python objects and classes
About Python variables and objects
About Python, len () and randint ()
About Python datetime and timezone
About Python and regular expressions
Python # About reference and copy
About Python sort () and reverse ()
About _ and __
About installing Pwntools and Python2 series
About python dict and sorted functions
About dtypes in Python and Cython
About Python pickle (cPickle) and marshal
[Python] About Executor and Future classes
About Python, from and import, as
Python os related files, subdirectory operations
About python slices
About python comprehension
About Python tqdm.
About python yield
About python, class
About python inheritance
Python OS operation
About python, range ()
About python decorators
A story about Python pop and append
About python reference
About Python decorators
[Python] About multi-process
Talking about old and new Python classes
My os (python)
Talking about Python class attributes and metaclasses
Think about depth-priority and width-priority searches in Python
About the difference between "==" and "is" in python
A story about modifying Python and adding functions
[Python] Learn about asynchronous programming and event loops
About the * (asterisk) argument of python (and itertools.starmap)
About shallow and deep copies of Python / Ruby
About Python for loops
Summary about Python scraping
File operations in Python
About function arguments (python)
OS and Linux distribution
Python and numpy tips
[Python] File / directory operations
[Python] pip and wheel
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
[Python] Memo about functions
Ruby, Python and map
Summary about Python3 + OpenCV3
About Python3 character code
File operations in Python
Python and Ruby split
About Python development environment
Python: About function arguments
Python, about exception handling
About Python Pyramid traversal
About Python3 ... (Ellipsis object)