Day 66: Being A Scribe – Read From And Write To Files

# Read and write files

# open the file with 'write'-mode
test_file = open("files_test.txt", "r")


# full list of file modes
# "w" - write text file (overwrite possible)
# "r" - read text file
# 'x' - write text file (includes error is file exists)
# 'a' - append to end of file
# 'rb' - read binary files
# 'wb' - write binary
# 'w+b' - read and write binary file
# 'xb' - write binary file (includes error is file exists)
# 'ab' - append to end of binary file

# Read files
print(test_file.read())                     # This is a test - full text

# Read one line
print(test_file.readline())                  # This is a test - one line


# iterate over text files
for line in test_file:
    print(line)                              # This is a test - all lines

# readline() is not very well suited to iterate over big files

# close files - you should alway close a file after using it!!!
test_file.close()

# Write to files
texty = open("files_test.txt", 'w')
texty.write("11 This is a test\n")
print(texty.read())
texty.close()

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.