Python: File Handling [Input/Output]

Let’s create a file named “product1.txt“, and add the content-

Product name: Sonic Wireless Headphones (Model XYZ)
Model: SWH-30G21
Category: Electronics/Audio/Headphones
description: Crystal-clear audio, BT 5.0, ANC, 30h playtime, microphone, voice assistant, foldable
Color: Black
Weight: 0.5lbs (227g)
Battery Life: 30h (off ANC), 20h (on ANC)
Range: 30ft (10m)
Speaker Size: 40mm
Price: $99.99
Plaintext

Read File Line by Line

Now we can read the file content line by line using the following code-

# Open the file
product_info = open('product1.txt')

# Read the file line by line
for info in product_info:
    # Print content of the file
    print(info)
Python

Output:

Product name: Sonic Wireless Headphones (Model XYZ)

Model: SWH-30G21

Category: Electronics/Audio/Headphones

description: Crystal-clear audio, BT 5.0, ANC, 30h playtime, microphone, voice assistant, foldable

Color: Black

Weight: 0.5lbs (227g)

Battery Life: 30h (off ANC), 20h (on ANC)

Range: 30ft (10m)

Speaker Size: 40mm

Price: $99.99
Plaintext

Read Full File Content

# Open file
product_info = open('product1.txt')

# Read entiner file content
full_input = product_info.read()

# Check the type of result returned by read()
print("Type of full_input: ", type(full_input))

# Print the content
print("Content:")
print(full_input)
Python

Output:

Type of full_input:  <class 'str'>


Content:

Product name: Sonic Wireless Headphones (Model XYZ)
Model: SWH-30G21
Category: Electronics/Audio/Headphones
description: Crystal-clear audio, BT 5.0, ANC, 30h playtime, microphone, voice assistant, foldable
Color: Black
Weight: 0.5lbs (227g)
Battery Life: 30h (off ANC), 20h (on ANC)
Range: 30ft (10m)
Speaker Size: 40mm
Price: $99.99
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.