Skip to content

Basics #1143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open

Basics #1143

Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
_file Finished
  • Loading branch information
clbmiami2004 committed Sep 6, 2020
commit 2f8f0083caa5e2e167a4e1e4dcf9c701b6a97183
32 changes: 31 additions & 1 deletion src/13_file_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,40 @@
# Note: pay close attention to your current directory when trying to open "foo.txt"

# YOUR CODE HERE
import os.path

# get the file relative file to the current script
my_path = os.path.dirname(__file__)
foo_path = os.path.join(my_path, 'foo.txt')

with open(foo_path) as f:
print('Contents of \'foo.txt\':')
for line in f:
print(' ' + line, end='')

f.close()

# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
# then close the file. Open up "bar.txt" and inspect it to make
# sure that it contains what you expect it to contain

# YOUR CODE HERE
# YOUR CODE HERE
arbitrary_text = '''First line of arbitrary text.
Second line of arbitrary text.
Third line of arbitrary text.'''

bar_path = os.path.join(my_path, 'bar.txt')

# Create (or override existing) file and write arbitrary text
with open(bar_path, 'w') as f:
f.write(arbitrary_text)

f.close()

# Open newly created file and print its contents
with open(bar_path) as f:
print('\nContents of \'bar.txt\':')
for line in f:
print(' ' + line, end = '')
f.close()
3 changes: 3 additions & 0 deletions src/bar.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
First line of arbitrary text.
Second line of arbitrary text.
Third line of arbitrary text.