Skip to content

Latest commit

 

History

History
38 lines (29 loc) · 668 Bytes

io.md

File metadata and controls

38 lines (29 loc) · 668 Bytes
layout
default

IO

Reading Files

# Opening a file for reading
with open(filename) as file:
    # Use file

# Reading entire contents as a single string
with open(filename) as file:
    contents = file.read()

# Iterating over lines, one by one
with open(filename) as file:
    for line in file:
        # Process line

Writing Files

# Opening a file for writing
with open(filename, 'w') as out:
    # use out

# Writing to file
with open(filename, 'w') as out:
    out.write(string)  # Does not add newline!

# Writing to file using print
with open(filename, 'w') as out:
    print(string, file=out) # Does add newline!