top of page

File System Object

# --- File - Write Data to File ---
# ------------------- Create Export String ---------------------- 

mytext_var = 'This will be a long string\n'
mytext_var += 'I Will add more to each line '
mytext_var += 'in this vairable to make a paragraph.'

# --- File Object with (w) write process open ---
myfile = open( 'c:/Python/Sample/Sample.txt','w')

# --- File (Over)Writting Process ---
myfile.write(mytext_var)
myfile.close()

# ---------------- File - Display Contents to Screen -------------
file = open('c:/Python/Sample/Sample.txt','r')
for line in file:
    print(line)
file.close()

 


# -------------- Data to write array to the file -----------------
data = [
    "\nThis is the first line.",
    "This is the second line.",
    "Here's the third line of text."
]

 


# ------------ Function Append (a) file ---------------
def write_to_txt(file_name, data):
    with open(file_name, mode='a', encoding='utf-8') as file:
        for line in data:
            file.write(line + '\n')
    print(f"\nData successfully written to {file_name}")

if __name__ == "__main__":
    file_name = 'c:/Python/Sample/Sample.txt'
    write_to_txt(file_name, data)

 


# --- File --- Display New Contents to Screen ---
print('\n--- New File Contents ---')
file = open('c:/Python/Sample/Sample.txt','r')
for line in file:
    print(line)
file.close()
 

# --------- Open and Read File and Search for String --------
# --- File open for Read ---

file = open('c:/Python/Sample/Sample.txt','r')
# --- Line Counter
LinePlacement=1
# --- Loop to Read File Line by Line
for line in file:
    # --- Conditional to Seach for Char in Line 
    if('Three' in line):
        # --- If Found Write that Line and the Line Number to Screen
        print(line)
        print(LinePlacement)
    # --- Incriment Line Number 
    LinePlacement+=1
# --- Close File
file.close()

 

 


# --------- Open and Read File and Search & Replace String --------
# --- Open File Path 

file_path = 'c:/Python/Sample/Sample.txt'

# String to search for and its replacement
search_string = '1'
replacement_string = 'Three'

# Read the file and modify its content
with open(file_path, 'r') as file:
    lines = file.readlines()

# Open the file for writing to overwrite with the updated content
with open(file_path, 'w') as file:
    for line in lines:
        # Replace the string in the line if found
        updated_line = line.replace(search_string, replacement_string)
        file.write(updated_line)

file.close()
 

bottom of page