Cheatography
https://cheatography.com
basic file handling in python
open()
open() |
("filename","mode",enconding="UTF-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.read() |
file.read(5) |
reads the first 5 characters |
readline() |
file.readline() |
returns one line of the file |
file.readline(5) |
reads the fist 5 characters of the line |
file.readline() / file.readline() |
calling readline two times, reads the two first lines |
readlines() |
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.write("text") |
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 |
writelines() |
turns iterable object(lists,tuples,dict...) into lines in the file |
|
|
pointers
seek(offset,whence=0)) |
changes the file position |
file.seek(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.tell() |
returns the file position |
close()
close() |
always close the file when done |
file.close() |
Modules
import os |
OS module |
os.rename("oldname.txt", "new_name.txt") |
os.remove("file.txt") |
os.path.exists("file.txt") or os.path.isfile() |
returns True or False |
os.path.getsize("file.txt") |
return |
os.path.getmtime("file.txt") |
returns a timestamp |
os.path.abspath("file.txt") |
returns Absolute Path |
os.getcwd |
show current working directory |
os.mkdir("new_dir") |
create new directory in the current dir |
os.chdr("dir") |
change working directory |
os.rmdir("dir") |
removes empty directory / error if there is files in it |
os.listdir |
return a list of files e subdirectories in the dir |
os.path.isdir |
os.path.join |
import datetime |
Datetime Module |
datetime.date |
os.path module docs |
|
os module docs |
|
datetime module docs |
|
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by corisco