Files: Difference between revisions
Appearance
No edit summary |
|||
Line 7: | Line 7: | ||
path = Path('gravitys_rainbow.txt') # specify path to file (in current directory) | path = Path('gravitys_rainbow.txt') # specify path to file (in current directory) | ||
try: # begin error handling | try: # begin error handling | ||
contents = path.read_text().rstrip() # read | contents = path.read_text().rstrip() # read contents into a string, removing any whitespace | ||
print(f'File as one string:\n{contents}') | print(f'File as one string:\n{contents}') |
Revision as of 15:49, 13 May 2024
Note: VC Code does not, by default, run python files in the directory where they are saved. To change this behavior, click Code > Settings > Settings, search for "python.terminal.executeInFileDir", and enable it.
Read from a File
from pathlib import Path
path = Path('gravitys_rainbow.txt') # specify path to file (in current directory)
try: # begin error handling
contents = path.read_text().rstrip() # read contents into a string, removing any whitespace
print(f'File as one string:\n{contents}')
lines = contents.splitlines() # separate file by line breaks
print('File as one string per line:')
for line in lines:
print(line)
except FileNotFoundError: # If file not found
print(f"Sorry, the file {path} does not exist.")
Write to a File
from pathlib import Path
gr = "A screaming comes across the sky. "
gr += "It has happened before, but there is nothing to compare it to now. "
gr += "It is too late. The evacuation still proceeds, but it's all theatre."
gr_file = Path('gravitys_rainbow.txt') # creates file if it doesn't exist
gr_file.write_text(gr)