Basic Python

os, getcwd, listdir, rename, startswith, endswith, input

Naranjito 2021. 5. 7. 16:07
  • os

Operating System, provides functionality on the Operating System such as copy the file, create the directory, etc.

 

  • getcwd

Get Current Working Directory, returns a string representing the current working directory.

import os 
os.getcwd()
>>>
'/Users/joohyunyoon/workspace/practice/src'

 

  • listdir

List directory, returns a list containing the names of the entries in the directory.

os.listdir()
>>>
['businesscard.ipynb', '__pycache__', 'hr.py', 'program.py']

 

  • rename

It renames a source file/directory to specified destination file/directory.

f='/Users/joohyunyoon/Downloads/Book_sell.csv'
new_f='/Users/joohyunyoon/Downloads/Book_sell_new.csv'
os.rename(f,new_f)

Rename the f path to new_f path.

 

  • startswith

It returns True if the string starts with the specified value, otherwise False.

file_name = "2020_보고서.xlsx"
file_name.startswith('2020')
>>>
True

 

  • endswith

It returns if the string ends with the specified value.

for x in os.listdir('/Users/joohyunyoon/workspace/practice/src'):
    if x.endswith('py'):
        print(x)
>>>
hr.py
program.py

 

  • input

It allows user input.

def set_contact():
    name=input('name:')
    mobile=input('mobile:')
    email=input('email:')
    addr=input('addr')
    print(name,mobile,email,addr)