Back
Close

Computing with Data

elgeish
33.2K views
Previous: Regression Next: Reading and Writing Ndarrays

Reading and Writing Data in Text Format

Below are a few examples of how to read from a text file or write to a text file in Python:

# Example: read a text file line by line using a for-loop
f = open("mobydick.txt", "r") # open file for reading
words = []
for line in f: # iterate over all lines in file
words += line.split() # append the list of words in line
f.close()
# Example: the with statement
with open("mobydick.txt") as f: # "rt" is the default mode
words = [word for line in f for word in line.split()]
# Example: writing to a file
with open("output.txt", "w") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])
with open("output.txt") as f:
print(f.read())
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants