Show Menu
Cheatography

File handling in python Cheat Sheet (DRAFT) by

How to use basic file handling features in python

This is a draft cheat sheet. It is a work in progress and is not finished yet.

opening/ creating files

file = open("Names.txt","a")
file is a variable that the new text file will be stored in.
open is a command that checks for the file, if it does not exist it makes a new one.
.txt will open a file in notepad, .docs or .text can be used as altern­atives.
a means append, this allows you to add data to the end of the file.
 

writing to a file

file = open("Scores.txt","a")
name = input("Enter name: ")
score = input("Enter score: ")
file.write(name + "/ " + score "\n")
file.close()
print("Score added")
.write() line writes what is in the brackets to the text file.
.close() must be used to close the file or the contents of it will not be saved.
Note that you can also add variations to the .write line by adding " ", "­\n", to add a space between each bit of data or separate it onto different lines.
The "­+" symbol is used for writing more than one variable in a line and each needs to be separated by a dash.