import os
current_file = os.path.realpath('file_io.ipynb')
print('current file: {}'.format(current_file))
# Note: in .py files you can get the path of current file by __file__
current_dir = os.path.dirname(current_file)
print('current directory: {}'.format(current_dir))
# Note: in .py files you can get the dir of current file by os.path.dirname(__file__)
data_dir = os.path.join(current_dir, 'data')
print('data directory: {}'.format(data_dir))
print('exists: {}'.format(os.path.exists(data_dir)))
print('is file: {}'.format(os.path.isfile(data_dir)))
print('is directory: {}'.format(os.path.isdir(data_dir)))
file_path = os.path.join(data_dir, 'simple_file.txt')
with open(file_path, 'r') as simple_file:
for line in simple_file:
print(line.strip())
new_file_path = os.path.join(data_dir, 'new_file.txt')
with open(new_file_path, 'w') as my_file:
my_file.write('This is my first file that I wrote with Python.')
Now go and check that there is a new_file.txt in the data directory. After that you can delete the file by:
if os.path.exists(new_file_path): # make sure it's there
os.remove(new_file_path)