Show Menu
Cheatography

Files Python Cheat Sheet (DRAFT) by

asddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

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

File Modes

Method­/Ke­yword
Meaning
r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
w
Opens a file for writing only, truncating the file first. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
x
Opens for exclusive creation, failing if the file already exists
a
Opens a file for writin­g/a­ppe­nding. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
+
Open for updating (reading and writing)
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
b
Binary mode
sdffds
kjhljhk
kjhjhk
hjkjkh
hjkjkh
hjkjh
hkjjkh
jhkjhkhjk
ghjkghj
hgjhjghjg
hjghjg­hjh­jghgj
jhgghj­ghjhgj
ghghjhjg
jghghj
jghjhgjhg
hgjjhgghj
ghjghjghj
hgjghjghj
jhgghjghj
hjgjhg­ghjjh
ghjhgjghj
hgjhjg
jhggjhjhg
hgjjhgjhg
gjhjhghjg
hgjhjg­jhgjhg
ghjghjgjh
ghjhjghjg
jghjhghgj
ghjhjg­jghjgh
ghgjhgjh
ghjjhgjhg
ghjghgjhjg
hgjjghgjh
ghjjghgjh
hgjjgh­jghghj
hjghjg­jghjhg
jjhggjhhjg
jhghjg­hjggjh
hjghgj­jghjhg
gjhhjgjgh
hgjjhghjg
hjghgj­gjhgjh
hjgjhg­jhgghj
hgjhjg­ghjghj
jhghgj­hjghgj
hjgjhg­jhgjhg
hgjjhg­hjgjhg
jhgjhg­hjg­jhghjg
ghjghj­hgj­gjhgjh
jhgghj­hgj­hjgjhg
hjghjg­hjg­hjgjhg

Functions

Method­/Ke­yword
Parameters
Uses
open()
filename and open mode (optional)
create a file object by openin­g/c­reating the file in the specified read/write mode
with
-
use it together with open(); closes the file after the suite completes
read()
size (optional)
read the file up to the size specified if set
readline()
size (optional)
read a single line with a size limit if set
readli­nes()
size (optional)
create a list of the read lines with an optional size hint
write()
the string
write the string to the file that is opened with a certain writeable mode
writel­ines()
the list of strings
write the list of strings to the file that is opened with a certain writeable mode
seek()
offset, whence­=SE­EK_SET
Change the stream position to the given byte offset
truncate()
size=None
Resize the stream to the given size in bytes (or the current position if size is not specif­ied).

File Modes

Start
Read
Write
Create
Truncate
Cursor
r
*
     
Start
w
 
*
*
*
Start
a
 
*
*
 
End
r+
*
*
   
Start
w+
*
*
*
*
Start
a+
*
*
*
 
End
x
   
*
 
Start

readline()

with open('test.txt') as file:
    file.readline()           
    file.readline(2) # 2 characters from line 2
    file.readline(5) # 3 characters from line 3
    file.readline()  
    file.readline()

'0 Start Line 0 - Line 0 End 0\n'
'1 '
'Start'
' Line 1 - Line 1 End 1\n'
''
If you call the readline() method multiple times, the reading will be continued at where it was read last time.
readline() method can also take in a size parameter, which will be used as a limit for reading the line. Again, reading is continued at where it was read last time.

Write a File

with open('test.txt', 'w') as file:             
    file.write('This is a writing method.')

25
The w mode will truncate the file, and thus the file will only contain the new values. The a mode will allow you to append new values to the existing file.
Printing the number of characters written can be suppressed by assigning the returned value to an unders­core.

Reading Different Types of CSV

import csv
 
with open('addresses.csv', newline='') as addresses_csv:
  address_reader = csv.DictReader(addresses_csv, delimiter=';')

  for row in address_reader:
    print(row['Address'])
We change the delimiters to indicate where the different values start and stop. We pass delimiter parameter, which is used to delineate separate fields in the CSV.

Writing a CSV File

big_list = [{'name': 'Fredrick Stein', 'userid': 6712359021, 'is_admin': False}] 
 
import csv
 
with open('output.csv', 'w') as output_csv:
  fields = ['name', 'userid', 'is_admin']
  output_writer = csv.DictWriter(output_csv, fieldnames=fields)
 
  output_writer.writeheader()

  for item in big_list:
    output_writer.writerow(item)
Open CSV in write mode, define fields, instan­tiate CSV writer object and pass two arguments.

.write­hea­der() writes headers from fieldn­ames.
 

Read File

with open('test.txt') as file: 
    file.read(6) # Size smaller than file size

'0 Star'
When the size argument is omitted or set as negative, or set as an integer greater than the file size, all the file contents will be read.

Reading a file for the second time will return an empty string.

readli­nes()

with open('test.txt') as file:
    file.readlines()
    # file.readlines(29) reads 29 characters, 30 reads whole of next line

['0 Start Line 0 - Line 0 End 0\n', '1 Start Line 1 - Line 1 End 1\n']
When size is set as a positive integer, it will read that many characters (or bytes in the binary mode) from the file and enough to complete that line.

writel­ines()

with open('test.txt', 'w') as file: 
    file.writelines(['Line 0\n', 'Line 1'])


with open('test.txt') as file:     
    file.read()

'Line 0\nLine 1'
This method will take in a list of strings as the parameter. How the lines are written (e.g., overwr­iting or appending) using this method is similar to the implem­ent­ation of the write() method.

What is a CSV File?

Comma-­Sep­arated Values are usually the way that data from spread­sheet is exported into a portable format.

Reading a CSV File

import csv

list_of_email_addresses = []
with open('users.csv', newline='') as users_csv:
  user_reader = csv.DictReader(users_csv)
  for row in user_reader:
    list_of_email_addresses.append(row['Email'])
We can convert data into a dictionary using *csv and its DictReader object.
newlin­e=""' ensures that we don’t mistake a line break in one of our data fields as a new row in CSV.