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): os.makedirs(newpath) print("Folder created.") else: print("Folder already exists.")
Writing to a file
myfile = open("hello.txt", "w") myfile.write( "Hello world!") myfile.close()
Create a new folder and write a file inside it
import os myfolder = r'C:\newfolder' os.makedirs(myfolder) myfile = open(myfolder + "\hello.txt", "w") myfile.write( "Hello world!") myfile.close()
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") myfile.write(longstring) myfile.close()
Creating a list and loop through it
numbers = ["one", "two", "three"] i = 0 while i < len(numbers): print(numbers[i]) 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]: print(prop) i += 1