Python

Table of Contents

Files and Directories

File Modes in Python


Directories (Folders)

First find the current Directory you are working with
>>>os.getcwd() ''C:\\WINDOWS\\system32''


To list directories use the os method os.listdir()
>>>os.listdir("C:\\")


Nesting directories
os.listdir(os.getcwd())


To change the directory use os.chdir(path) where path is substituted for the target location
os.chdir(path)


e.g. To change to another windows directory use
>>>os.chdir('C:\\users\USER\desktop')


Or to move up a directory
>>>os.chdir('..')


Make directory
>>>os.mkdir("Directory_Name")


Start by changing to your desktop directory to find the files we will be creating easier And to delete them.

>>>os.chdir('C:\\users\USER\desktop')


To remove file/directory
Note the below options will delete the file from the system and will not be recoverable by default.
1)
os.remove()
will remove a file.
2)
os.rmdir()
will remove an empty directory.
3)
shutil.rmtree()
will delete a directory and all its contents.

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode. If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating) /td>


>>>txt_object=open("test.py","w+")
This creates a new python file on our desktop.

>>>txt_object.write("This adds text to file")
.write method writes text to file

>>>txt_object.close()
closes the file to stop further amendments thus saving the newly created file.

To then read the contents of the file to the shell host output
>>> txtfile_objectput=open("demo_string_input.py", "r") >>> print(txtfile_objectput.read())


To add new lines to the file then reopen again

>>>txt_object=open("test.py","a+")
Then write
>>>txt_object.write("Foo Foo Foobar")
Then close again
>>>txt_object.close()

Visit next page to learn about - Objects