Skip to content
  • Reading & Writing Files · Data Science

Reading & Writing Files

LearnViaNotes @learnvianotes· 3 min read

Most data science starts with a file. Python's built-in open() reads and writes text files — and a few string methods already give you basic text statistics.

Modes

ModeMeaningIf the file existsIf it doesn't
'r'Read (default)Reads from the startFileNotFoundError
'w'WriteErases it firstCreates it
'a'AppendWrites at the endCreates it
'r+'Read and writeStarts at the beginningFileNotFoundError
'x'Create onlyFileExistsErrorCreates it

Writing: write vs writelines

Python
lines = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
with open("myfile.txt", "w", encoding="utf-8") as f:
    f.write("Hello \n")          # one string
    f.writelines(lines)          # an iterable of strings (no newlines are added for you)

with open("myfile.txt", encoding="utf-8") as f:
    print(f.read())
Output
Hello
This is Delhi
This is Paris
This is London

Reading: read, readline, readlines, seek

Python
with open("myfile.txt", encoding="utf-8") as f:
    print(repr(f.read(9)))       # 'Hello \nTh'   ← 9 characters, across lines
    f.seek(0)                    # jump back to the start
    print(repr(f.readline()))    # 'Hello \n'     ← up to and including the newline
    f.seek(0)
    print(f.readlines())         # ['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
MethodReturns
f.read() / f.read(n)The whole file / the next n characters, as one string
f.readline()The next line, including its \n
f.readlines()A list of all remaining lines
for line in f:Lines one at a time — memory-friendly for big files
f.seek(n)Moves the position to byte n (0 = start)

Append vs write

Python
with open("notes.txt", "w") as f:
    f.write("Today \n")
with open("notes.txt", "a") as f:        # append keeps what was there
    f.write("Tomorrow \n")
with open("notes.txt") as f:
    print(f.readlines())                  # ['Today \n', 'Tomorrow \n']

with open("notes.txt", "w") as f:        # write erases it first
    f.write("Only this \n")
with open("notes.txt") as f:
    print(f.readlines())                  # ['Only this \n']

Quick text statistics

Python
text = """Data science turns raw data into insight. It mixes statistics and programming.

Python is the most popular language for it."""

paragraphs = [p for p in text.split("\n\n") if p.strip()]
sentences = [s for s in text.replace("\n", " ").split(".") if s.strip()]
words = text.split()                     # split() with no argument handles any whitespace

print(len(paragraphs), len(sentences), len(words))   # 2 3 20

Cleaning unwanted characters

Python
raw = "Hello!! World@ #2026 [7] [12]"
for ref in [f"[{i}]" for i in range(1, 20)]:     # remove citation markers like [7]
    raw = raw.replace(ref, "")
for ch in "!@#":                                 # remove unwanted symbols
    raw = raw.replace(ch, "")
print(" ".join(raw.split()))                     # Hello World 2026

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report