Monday, March 27, 2017

Working with files in Python

Some notes about working with files in Python.

How simply generate path:

import os
os.path.join('usr', 'user', 'Documents')

or if we need path to file:

os.path.join('home/Documents/work', important.txt)

os.getcwd()check current directory

os.chdir('path to new working directory')change directory

os.makedirs('home/docs/test')create directory

os.path.abspath('path')get absolute path

os.path.relpath('path', 'start point')get relative path

os.path.dirname('path')get directory name actually will return name with whole path

os.path.basename('path')get file name

os.path.split('path')to get both directory name and file name as a tuple

or 

examplePath.split(os.path.sep) - will return tuple where every directory and file name are separate strings (in OSX first item in the list will be '')

os.path.listdir('path')list all items in the directory

os.path.getsize('path')get file size in bytes

os.path.exists('path') - returns True if directory or file exists

os.path.isfile('path') - returns True if file exists

os.path.isdir('path') - returns True if directory exists

open('path') - returns file object if there's no such file Python will create that

read('path') or open('path', 'r')- reads file

file.readlines() - reads line by line from file

write('path') or open('path', 'w')- writes to file (simple usage will overwrite all content)

open('path', 'a') - will append text to the end of the file instead of overwriting

close('path') - closes file


Work with binary shelf files (can be used as dictionaries etc.):

import shelve
testFile = shelve.open('filename')
testValues = ['email', 'address', 'phone']
testFile['data'] = testValues
testFile.close()

testFile('data') - prints out values

list(testFile.keys()) - prints list of keys in our case it will be just 'data'

list(testFile.values()) - prints list of values ie ['email', 'address', 'phone']

import pprint
pprint.pformat(list) - will represent list / dictionary as a string for easier saving that to a file

And for the end short reminder about shelf files and plain text files: first used mostly for complex objects (ie file objects) while plain text files can be used for storing simple data (ie text, integers etc)


No comments:

Post a Comment