---
# System prepended metadata

title: File I/O

---

###### tags: python

# File I/O

my_file = open('text.txt')
print(my_file.read())
print(my_file.readline())
print(my_file.readlines()) --> output a list
my_file.close()

with open('test.txt', mode=
'r+') as my_file: r+ --> read and write
    text = my_file.write('hey it\'s me!')
    print(text) --> output numbers of characters

mode='a' --> append after the last word
mode='w' --> take the file as new and overwrite it or creat a new file if the file name does not exist
**../** app/sad.txt -->back to the folder

try:
    with open('sad.txt', mode='r') as my_file:
        print(my_file.read())
except FileNotFoundError as err:
    print('file does not exist')
    raise err
    
try:
    with open('sad.txt', mode='x') as my_file:
        print(my_file.read())
except IOError as err:
    print('IO error')
    raise err