Skip to content

Instantly share code, notes, and snippets.

@paulocheque
Last active December 21, 2015 02:09
Show Gist options
  • Save paulocheque/6233321 to your computer and use it in GitHub Desktop.
Save paulocheque/6233321 to your computer and use it in GitHub Desktop.
Python dealing with files
# -*- coding: utf-8 -*-
import os
import tempfile
from shutil import rmtree, copy2
TEMP_PATH = tempfile.gettempdir() or os.environ.get('TEMP')
def create_temp_directory(prefix='temp_dir_'):
"Create a temporary directory and returns the directory pathname."
return tempfile.mkdtemp(prefix=prefix)
def remove_temp_directory(directory_pathname):
"Remove a directory."
rmtree(directory_pathname)
def create_temp_file(directory=None, prefix='temp_file_', suffix='.tmp'):
"""
Create a temporary file with a option prefix and suffix in a temporary or custom directory.
Returns the filepath
"""
fd, path = tempfile.mkstemp(prefix=prefix, dir=directory, suffix=suffix)
return path
def create_temp_file_with_name(directory, name):
"Create a temporary file with a specified name."
filepath = os.path.join(directory, name)
file_obj = open(filepath, 'wb')
file_obj.close()
return filepath
def rename_temp_file(filepath, name):
"Rename an existent file. 'name' is not a file path, so it must not include the directory path name."
directory = get_directory_of_the_file(filepath)
new_filepath = os.path.join(directory, name)
os.rename(filepath, new_filepath)
return new_filepath
def remove_temp_file(filepath):
"Remove a file."
if os.path.exists(filepath):
try:
os.unlink(filepath)
except WindowsError:
pass
def copy_file_to_dir(filepath, directory):
"Copy a file to a specified directory."
copy2(filepath, directory)
return get_filepath(directory, get_filename(filepath))
def add_text_to_file(filepath, content):
"Add text to an existent file."
the_file = open(filepath, 'a')
the_file.write(content)
the_file.close()
def get_directory_of_the_file(filepath):
"Get the directory path name of a file."
return os.path.dirname(filepath)
def get_filename(filepath):
"Get the filename of a file."
return os.path.basename(filepath)
def get_filepath(directory, filename):
"Get the file path of a file with a defined name in a directory."
return os.path.join(directory, filename)
def get_content_of_file(filepath):
"Returns the content of a file."
the_file = open(filepath, 'r')
content = the_file.read()
the_file.close()
return content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment