Write To and Read Files with Python (Python Part 9)

  • 00:00 Intro
  • 02:18 Permissions
  • 05:51 Write to File
  • 10:22 Write HTML to File
  • 15:41 ACII Formatting Text
  • 18:35 Read File Into Variable Value
  • 22:54 File Modes
  • 33:34 Change File Path
  • 41:29 Change Current Working Directory
  • 43:59 Create an HTML Report from CSV Example
  • 59:10 Final Thoughts

File Modes:

  • w – overwrite
  • a – append to end
  • a+ – create file if does not exist
  • r – read
  • r+ – create file if does not exist
  • rb – read in bytes (multimedia file)
  • wb – write in bytes (multimedia files)

write.py

file = open('test.txt', 'w')
file.write('hello from FIRST example')
file.close()

with open('test2.txt','w') as file2:
  file2.write('hello from the SECOND example')

web.py

message = '''<h1>TITLE</h1>
             <p>This is a website</p>
             <p style="color:red;">Isn't it Cool!</p>
            '''

with open('web.html','w') as file2:
  file2.write(message)

text.py

message = 'This\t is\t a way to\t format\n text'

with open('text.txt','w') as file:
  file.write(message)

read.py

file = open('test.txt', 'r')
message = file.read()
file.close()

print(message)

with open('test2.txt', 'r') as file2:
  message2 = file2.read()

print(message2)

file-path.py

import os

file = open('test3.txt', 'w')

file.write('hello from the PATH example')

file.close()

print(os.getcwd())
print(os.path.dirname(os.path.realpath(__file__)))

directory = os.path.dirname(os.path.realpath(__file__))
print(directory)

file_path = os.path.join(directory,'test4.txt')
print(file_path)

file = open(file_path,'w')
file.write('hello from NEW FILE PATH')
file.close()

path-cwd.py

import os

print(os.getcwd())

new_directory = '/'

os.chdir(new_directory)

print(os.getcwd())

example.py

with open('data.txt', 'r') as file:
    record = file.read()

print(record)

record = record.split('\n')

print(record)

with open('report.html', 'w') as report:
    report.write('<table>')
    for student in record:
        if 'large' in student:
            value = student.split(',')
            result = '<tr>'
            for item in value:
                result += f'<td>{item}</td>'
            report.write(f'{result}</tr>')
    report.write('</table>')

data.txt

bob, 12, large, boy
sue, 33, small, girl
fred, 47, medium, boy
paul, 22, large, boy
tim, 21, small, boy
patty, 20, medium, girl
sally, 15, large, girl 

Be the first to comment

Leave a Reply