Created
November 3, 2022 02:08
-
-
Save lundeen-bryan/cf1f4d8ddda02f47448f5cea63dc25dc to your computer and use it in GitHub Desktop.
file read write util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from os import path, sys | |
def read_file(file_name): | |
file_name = os.path.join(sys.path[0], file_name) | |
if path.isfile(file_name): | |
with open(file_name, mode="r") as file: | |
contents = file.readlines() | |
return contents | |
else: | |
return f"{file_name} not found" | |
def write_file(file_name, new_text, overwrite=False): | |
ovr = "a" | |
if overwrite==True: | |
ovr = "w" | |
file_path = os.path.join(sys.path[0], file_name) | |
if file_path.find("/.") != -1: | |
file_path = file_name.replace("/.", "") | |
if path.isfile(file_path): | |
with open(file_path, mode=ovr) as file: | |
file.write(f"{new_text}") | |
else: | |
new_file(file_name, new_text) | |
def new_file(file_name, new_text): | |
file_path = os.path.join(sys.path[0], file_name) | |
if file_path.find("/.") != -1: | |
file_path = file_name.replace("/.", "") | |
with open(file_path, mode="w") as file: | |
file.write(f"{new_text}") | |
print(f"created: {file_path}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment