Thursday 25 April 2019

Tuesday 9 April 2019

Python Delete File

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example

Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example

Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Example

Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.

Python File Write

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Example

Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt""a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:f = open("demofile2.txt""r")
print(f.read())
Show Python »
C:\Users\My Name>python demo_file_append.py
Hello! Welcome to demofile2.txt            
This file is for testing purposes.         
Good Luck!Now the file has more content!   
                                           
                                           

Example

Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt""w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:f = open("demofile3.txt""r")
print(f.read())
Show Python »
C:\Users\My Name>python demo_file_write.py
Woops! I have deleted the content!        
                                          
                                          

Note: the "w" method will overwrite the entire file.

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

Example

Create a file called "myfile.txt":
f = open("myfile.txt""x")
Result: a new empty file is created!

Example

Create a new file if it does not exist:
f = open("myfile.txt""w")

Python File Open

Open a File on the Server

Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the file:

Example

f = open("demofile.txt""r")
print(f.read())
Show Python »
C:\Users\My Name>python demo_file_open.py
Hello! Welcome to demofile.txt           
This file is for testing purposes.       
Good Luck!                               
                                         
                                         


Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

Example

Return the 5 first characters of the file:
f = open("demofile.txt""r")
print(f.read(5))
Show Python »
C:\Users\My Name>python demo_file_open2.py
Hello                                     
                                          
                                          



Read Lines

You can return one line by using the readline() method:

Example

Read one line of the file:
f = open("demofile.txt""r")
print(f.readline())
Show Python »
C:\Users\My Name>python demo_file_readline.py
Hello! Welcome to demofile.txt               
                                             
                                             

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:
f = open("demofile.txt""r")
print(f.readline())
print(f.readline())
Show Python »
C:\Users\My Name>python demo_file_readline2.py
Hello! Welcome to demofile.txt                
This file is for testing purposes.            
                                              
                                              

By looping through the lines of the file, you can read the whole file, line by line:

Example

Loop through the file line by line:
f = open("demofile.txt""r")
for x in f:
  print(x)
Show Python »
C:\Users\My Name>python demo_file_readline3.py
Hello! Welcome to demofile.txt                
This file is for testing purposes.            
Good Luck!                                    
                                              
                                              


Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:
f = open("demofile.txt""r")
print(f.readline())
f.close()
Show Python »
C:\Users\My Name>python demo_file_close.py
Hello! Welcome to demofile.txt            
                                          
                                          

Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.

Python File Open

File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt""rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.

Python Try Except

The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement:

Example

The try block will generate an exception, because x is not defined:
try:
  print(x)
except:
  print("An exception occurred")
Show Python »
C:\Users\My Name>python demo_try_except.py
An exception occurred                     
                                          
                                          

Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:
print(x)
Show Python »
C:\Users\My Name>python demo_try_except_error.py      
Traceback (most recent call last):                    
  File "demo_try_except_error.py", line 3, in <module>
    print(x)                                          
NameError: name 'x' is not defined                    
                                                      
                                                      


Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Example

Print one message if the try block raises a NameError and another for other errors:
try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
Show Python »
C:\Users\My Name>python demo_try_except2.py
Variable x is not defined                  
                                           
                                           



Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:
try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
Show Python »
C:\Users\My Name>python demo_try_except3.py
Hello                                      
Nothing went wrong                         
                                           
                                           


Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")
Show Python »
C:\Users\My Name>python demo_try_except4.py
Something went wrong                       
The 'try except' is finished               
                                           
                                           

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:
try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()
Show Python »
C:\Users\My Name>python demo_try_except5.py  
Something went wrong when writing to the file
                                             
                                             

The program can continue, without leaving the file object open.

Python PIP

What is PIP?

PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.

What is a Package?

A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.

Check if PIP is Installed

Navigate your command line to the location of Python's script directory, and type the following:

Example

Check PIP version:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

Install PIP

If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/

Download a Package

Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:

Example

Download a package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase
Now you have downloaded and installed your first package!


Using a Package

Once the package is installed, it is ready to use.
Import the "camelcase" package into your project.

Example

Import and use "camelcase":
import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt))
Show Python »
C:\Users\My Name>python demo_camelcase.py
Lorem Ipsum Dolor Sit Amet               
                                         
                                         


Find Packages

Find more packages at https://pypi.org/.

Remove a Package

Use the uninstall command to remove a package:

Example

Uninstall the package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase
The PIP Package Manager will ask you to confirm that you want to remove the camelcase package:
Uninstalling camelcase-02.1:
  Would remove:
    c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2-py3.6.egg-info
    c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Press y and the package will be removed.

List Packages

Use the list command to list all the packages installed on your system:

Example

List installed packages:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list
Result:
Package         Version
-----------------------
camelcase       0.2
mysql-connector 2.1.6
pip             18.1
pymongo         3.6.1
setuptools      39.0.1