0% found this document useful (0 votes)
3 views15 pages

Understanding Text Files in Python

Python
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Understanding Text Files in Python

Python
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TEXT FILES IN

PYTHON
INTRODUCTION TO TEXT FILES
Text files store data as characters.
Commonly used for saving program
input/output.
Easier to create, read, and process
compared to binary files.
TEXT FILE FORMAT

A text file is a sequence of lines.


Each line ends with newline (\n).
Examples: .txt, .csv, .py.
WRITING TEXT TO A FILE
file = open("[Link]", "w")
[Link]("Hello, World!\n")
[Link]()

"w" mode: creates or overwrites file.


Must close file after writing.
WRITING NUMBERS TO A FILE
file = open("[Link]", "w")
for i in range(5):
[Link](str(i) + "\n")
[Link]()

Numbers must be converted to string.


Each number written line by line.
FILE MODES FOR WRITING
WRITING TO A FILE USING
WRITELINES() METHOD
# List of lines to write to the file
lines = ["First line\n", "Second line\n", "Third line\n"]
# Open a file in write mode
with open("[Link]", "w") as file:
[Link](lines)
READING TEXT FROM A FILE
file = open("[Link]", "r")
data = [Link]()
[Link]()
print(data)

"r" mode: read file.


read() reads entire content.
readline() reads one line at a time.
READING A FILE USING
READLINE() METHOD
# Open the file in read modefile =
open('[Link]', 'r')

# Read the first line of the file


line = [Link]()

# Print the lineprint(line)# Close the


[Link]()
READING A FILE USING READLINES() METHOD
# Open the file in read modefile =
open('[Link]', 'r')

# Read all lines from the file


lines = [Link]()

# Print the lines


for line in lines:print(line, end='')
# Close the file
[Link]()
USING "WITH" STATEMENT
"with" statement ensures that the file is
properly closed after reading, even if an
exception occurs

# Using the with statement to open a file

with open('[Link]', 'r') as file:


content = [Link]()
print(content)
READING NUMBERS FROM A FILE
file = open("[Link]", "r")
for line in file:
num = int(line)
print(num)
[Link]()

Convert text back to int using int().


Useful for numeric computations.
FILE AND DIRECTORY OPERATIONS
USING OS MODULE:
import os
[Link]() # Current directory
[Link]() # List files
[Link]("[Link]", "[Link]")
[Link]("[Link]")

Manage files and directories.


Check existence: [Link]("[Link]").
SUMMARY

Text files store data in readable format.


Modes: "w", "r", "a".
Always close files after use.
Use os module for file/directory handling.

You might also like