Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 14, 2011 13:20
Show Gist options
  • Save dketov/1476545 to your computer and use it in GitHub Desktop.
Save dketov/1476545 to your computer and use it in GitHub Desktop.
Работа с файловой системой
# -*- encoding: utf-8 -*-
"""
Пути к файлам и каталогам
"""
import os.path
for path in [ '/one/two/three', '/one/two/three/', '/', '.', '']:
print '"%s" : "%s"' % (path, os.path.split(path))
print '"%s" : "%s"' % (path, os.path.basename(path))
print '"%s" : "%s"' % (path, os.path.dirname(path))
paths = ['/one/two/three/four',
'/one/two/threefold',
'/one/two/three/']
print paths
print os.path.commonprefix(paths)
for parts in [ ('one', 'two', 'three'),
('/', 'one', 'two', 'three'),
('/one', '/two', '/three') ]:
print parts, ':', os.path.join(*parts)
for path in [ 'one//two//three',
'one/./two/./three',
'one/../one/two/three ]:
print path, ':', os.path.normpath(path)
for path in [ '.', '..', './one/two/three', '../one/two/three']:
print '"%s" : "%s"' % (path, os.path.abspath(path))
for file in [ __file__, os.path.dirname(__file__), '/', './broken_link']:
print 'File :', file
print 'Absolute :', os.path.isabs(file)
print 'Is File? :', os.path.isfile(file)
print 'Is Dir? :', os.path.isdir(file)
print 'Is Link? :', os.path.islink(file)
print 'Mountpoint? :', os.path.ismount(file)
print 'Exists? :', os.path.exists(file)
print 'Link Exists?:', os.path.lexists(file)
print
import os
os.getcwd()
os.path.abspath('')
os.path.abspath('.ssh')
os.path.abspath('/home/you/.ssh')
os.path.abspath('.ssh/../foo/')
# -*- encoding: utf-8 -*-
"""
Работа с файлами и каталогами
"""
import shutil
import os
os.mkdir('example')
print 'BEFORE:', os.listdir('example')
shutil.copy('shutil_copy.py', 'example')
print 'AFTER:', os.listdir('example')from shutil import *
from glob import glob
f = open('example.txt', 'wt')
f.write('contents')
f.close()
print 'BEFORE: ', os.listdir('.')
move('example.txt', 'example.out')
print 'AFTER : ', os.listdir('.')
# -*- encoding: utf-8 -*-
"""
Копирование дерева каталогов
"""
from shutil import copytree
def _ignore(path, names):
return [] # nothing will be ignored
copytree(source, destination, ignore=_ignore)
# -*- encoding: utf-8 -*-
"""
Создание временных файлов
"""
import tempfile
# read input file
inputFile = open('input.txt', 'r')
# create temporary file
tempFile = tempfile.TemporaryFile() # we don't even need to
first_process(input = inputFile, output = tempFile) # know the filename...
# create final output file
outputFile = open('output.txt', 'w')
second_process(input = tempFile, output = outputFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment