Files: Difference between revisions
Appearance
Created page with "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 == <syntaxhighlight lang="python" line> </syntaxhighlight> == Write to a File == <syntaxhighlight lang="python" line> </syntaxhighlight> <syntaxhighlight lang="python" line> </syntaxhighlight> <syntaxhighlight lang="python" line> </syn..." |
|||
Line 3: | Line 3: | ||
== Read from a File == | == Read from a File == | ||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
from pathlib import Path | |||
path = Path('pi_digits.txt') # locate file (in current directory) | |||
contents = path.read_text().rstrip() # read its contents into memory as 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) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== Write to a File == | == Write to a File == |
Revision as of 10:56, 21 April 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('pi_digits.txt') # locate file (in current directory)
contents = path.read_text().rstrip() # read its contents into memory as 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)
Write to a File