File Operations in Python: Difference between revisions
Jump to navigation
Jump to search
Line 41: | Line 41: | ||
print('getcwd:', os.getcwd()) | print('getcwd:', os.getcwd()) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Also see: {{Internal|Python_Module_os#Working_Directory|<tt>os</tt>}} | |||
=The Path of the Running Script File= | =The Path of the Running Script File= | ||
<syntaxhighlight lang='python'> | <syntaxhighlight lang='python'> | ||
print('__file__:', __file__) | print('__file__:', __file__) | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 00:53, 16 February 2022
Internal
Check whether a File Exists
import os.path
file_exists = os.path.exists(path_to_file)
Returns True
or False
.
from pathlib import Path
path = Path(path_to_file)
path.is_file()
Reading/Writing from/to Files
Read
f = open(filename, mode) c = f.read() f.close()
f = open('somefile', 'rt')
c = f.read()
f.close()
Mode: "r", "w", "x", etc. "t" text, "b" binary
Write
f = open('/Users/ovidiu/tmp/out.json', 'wt')
f.write("test\n")
f.close()
Working Directory
import os
print('getcwd:', os.getcwd())
Also see:
The Path of the Running Script File
print('__file__:', __file__)