Show Menu
Cheatography

file handling in python Cheat Sheet by

basic file handling in python

open()

open()
("fi­len­ame­"­,"mo­de",­enc­ond­ing­="UT­F-8­")
modes
"­r" - Read (default)
opens a file for reading, error if doesn´t exist
"­a" - Append
opens a file for appending, creates the file if doesn´t exist
"w' - Write
opens a file for writing, creates the file if doesn´t exist
"­x" - Create
creates the specified file, error if the file exists
"­t" - Text (default)
Text mode
"­b" - Binary
Binary mode
"­+" - Read and Write mode
opens a file to read or write
Examples
"­r+" "­a+b­" "­w+b­"

read()

read()
open() must have a read() method before.
file.r­ead()
file.r­ead(5)
reads the first 5 characters
readline()
file.r­ead­line()
returns one line of the file
file.r­ead­line(5)
reads the fist 5 characters of the line
file.r­ead­line() / file.r­ead­line()
calling readline two times, reads the two first lines
readli­nes()
returns a list, each item is a line as a string
for line in file
loops through the chars or lines of the file
 
use .strip() to remove "­\n"

write()

write()
open method "­a" will append to end of file
 
open method "­w" will overwrite the entire file
file.w­rit­e("t­ext­")
create a new file
open method "­x" will create a file, error if it exists
 
open method "­a" will create a file if doesn´t exist
 
open method "­w" will create a file if doesn´t exist
writel­ines()
turns iterable object­(li­sts­,tu­ple­s,d­ict...) into lines in the file
 

pointers

seek(o­ffs­et,­whe­nce=0))
changes the file position
file.s­eek(4)
change the pointer to the 4 file position
[whence=] is optional, 0 is default
0=start of file, 1=current position, 2= file´s end
tell()
finds the file position
file.t­ell()
returns the file position

close()

close()
always close the file when done
file.c­lose()

Modules

import os
OS module
os.ren­ame­("ol­dna­me.t­xt­", "­new­_na­me.t­xt­")
os.rem­ove­("fi­le.t­xt­")
os.pat­h.e­xis­ts(­"­fil­e.t­xt") or os.pat­h.i­sfile()
returns True or False
os.pat­h.g­ets­ize­("fi­le.t­xt­")
return
os.pat­h.g­etm­tim­e("f­ile.tx­t")
returns a timestamp
os.pat­h.a­bsp­ath­("fi­le.t­xt­")
returns Absolute Path
os.getcwd
show current working directory
os.mkd­ir(­"­new­_di­r")
create new directory in the current dir
os.chd­r("d­ir")
change working directory
os.rmd­ir(­"­dir­")
removes empty directory / error if there is files in it
os.listdir
return a list of files e subdir­ect­ories in the dir
os.pat­h.isdir
os.pat­h.join
import datetime
Datetime Module
dateti­me.date
os.path module docs
os module docs
datetime module docs
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by corisco

          strings, lists, tuples and dictionaries in python Cheat Sheet