Python useful snippets

In this post you can find useful and frequently used Python snippets. Just copy and paste it!

Creating new directory (folder)

import os

newpath = r'C:\mydirectory\newfolder' 
if not os.path.exists(newpath):
	print("Folder created.")
	print("Folder already exists.")

Writing to a file

myfile = open("hello.txt", "w")
myfile.write( "Hello world!")

Create a new folder and write a file inside it

import os
myfolder = r'C:\newfolder' 
myfile = open(myfolder + "\hello.txt", "w")
myfile.write( "Hello world!")

How to write a long multi line text into a file

longstring = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, 

sed do eiusmod tempor incididunt 
ut labore et dolore magna 
aliqua. Ut enim ad minim veniam, quis nostrud ...

exercitation ullamco laboris 
nisi ut aliquip ex ea commodo consequat. 


Duis aute irure dolor 
in reprehenderit 
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

myfile = open("hello.txt", "w")

Creating a list and loop through it

numbers = ["one", "two", "three"]
i = 0
while i < len(numbers):
    i += 1

Creating a nested list and loop through it again

projects = [
	[ 1, "One" ], 
	[ 2, "Two" ], 
	[ 3, "Three" ],
	[ 4, "Four" ],
	[ 5, "Five" ],

i = 0
while i < len(projects):
	for prop in projects[i]:
	i += 1

Leave a Reply

Your email address will not be published. Required fields are marked *