1. f=open('filename.txt', 'r')
  2. with open('filename.txt', 'r') as f:
  3. f.read()
  4. f.readline()
  5. f.read().strip()
  6. f.write('write this string\n')
  7. \n to add new line
  8. f.close()
  9. import os
  10. if os.path.exists('filename.txt')
  11. .strip() removes any trailing newline characters \n

1. to read an entire file

a. read()

with open('filename.txt','r') as f:
	print(f.read())

Outputs:

Beech,30,400,200,No
Hazel,40,300,200,No
Oak,5,900,600,No
Holly,30,600,300,Yes
Walnut,30,2500,1000,No
Magnolia Grandiflora,50,500,300,Yes
Photinia,30,400,400,Yes
Blue Conifer,40,250,50,Yes
Green Conifer,40,300,150,Yes

b. readlines() # list

with open('filename.txt','r') as file:#open() function
	lines=file.readlines()#read all lines and stores them in a list with each line ends with \n
	print(lines)# dont need to iterate because the list will be printed with each list element ends with \n

Outputs:

['Oak\n', 'Pine\n', 'Maple\n', 'Birch\n', 'Cedar\n']

each line is stored as a string inside the list
\n (newline character) is included at the end of each list element
if the file is large, readlines() might use a lot of memory because it loads all the lines at once

2. read first n lines of a file

a. iterate over the file lines

n=3
with open('Trees.txt','r') as f:
    for _ in range(n):
        print(f.readline().strip())#print a single string(next line)

b. iterate over the list

with open('Trees.txt','r') as f:#open() function
   lines=f.readlines()# lines as a list to store lists
   for i in range(n):# int object is not iterable 
       print(lines[i].strip())

3. read file line by line

with open('filename.txt','r'):#open() function
	for line in file:
		print(line.strip())

Pasted image 20250128221021.png|300

with open('filename.txt'):#open() function
	for line in file:
		print(line)

Pasted image 20250128220923.png|300

4. Errors

Issue:

You are using both:

for i in f:  # This already reads each line in the file     
j = f.readline().strip().split(',')`

Fixed code:

for line in f: # Read each line 
j = line.strip().split(',') # Split line into list

or

j= f.readline().strip().split(',')

using eof formula

def ReadData():
    array = []  # Array to store Tree objects
    try:
        with open('Trees.txt', 'r') as f:  # Open file for reading
            for line in f:  # Iterates over each line in the file
                line = line.strip()  # Remove trailing whitespace
                
                # Split the line into a list of values
                data = line.split(',')
                if len(data) == 5:  # Ensure we have 5 parameters
                    obj = Tree(data[0], data[1], data[2], data[3], data[4])  # Create Tree object
                    array.append(obj)  # Add object to array
                else:
                    print("Incorrect data format:", data)  # Handle incorrect data
        
        return array  # Return list of Tree objects
    
    except FileNotFoundError:
        print('File not found')
        return None

random file handling

image-56.png|667x370

  1. pickle
    • save python objects to a file/ byte stream
    • pickle.dump(object, file) -> save object into bin file
    • pickle.load(file) -> restore object from bin file

  1. datetime
    • asdf
  2. random file open convention(w/r/b/a)
import pickle
import datetime
class student:
    def __init__(self):
        self.name = ''
        self.registerNumber = 0
        self.dateOfBirth = datetime.datetime.now()
        self.fullTime = True

studentRecord = student()
with open('students.DAT','wb') as studentFile:
    #create a binary file to store data
    print('Please enter student details.')
    
    studentRecord.name = input('Enter student name: ')
    studentRecord.registerNumber = input('Register number: ')
    
    year = int(input('Enter year of birth (YYYY): '))
    month = int(input('Enter month of birth (MM): '))
    day = int(input('Enter day of birth (DD): '))
    
	studentRecord.dateOfBirth =datetime.datetime(year,month,day)

    #studentRecord.fullTime = bool(input('Please enter True for full time, False for part-time.'))
    fulltime_input = input('Is the student full-time? (True/False): ')
    studentRecord.fullTime = fulltime_input.strip().lower() == 'true'

    pickle.dump(studentRecord ,studentFile)
    #write record to file
    print('\nStudent saved.')
    print(studentRecord.name,studentRecord.registerNumber,studentRecord.dateOfBirth,studentRecord.fullTime)
    
with open('students.DAT','rb') as studentFile:
    studentRecord = pickle.load(studentFile)
    #read record from file
    print('\nStudent loaded from file:')
    print(studentRecord.name,studentRecord.registerNumber,studentRecord.dateOfBirth,studentRecord.fullTime)

import pickle

data = [1, 2, 3]
byte_data = pickle.dumps(data)  # dumps = "dump string"
print(byte_data)  # Output: b'\x80...'

# Restore from byte string
original = pickle.loads(byte_data)
print('\n')
print(original)  # Output: [1, 2, 3]

image-55.png