File Operations in Python: Difference between revisions
Jump to navigation
Jump to search
Line 15: | Line 15: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Reading/Writing from/to Files= | =Reading/Writing from/to Files= | ||
==Read== | |||
<font size=-1> | <font size=-1> | ||
f = open(''filename'', ''mode'') | f = open(''filename'', ''mode'') | ||
Line 29: | Line 30: | ||
Mode: "r", "w", "x", etc. "t" text, "b" binary | Mode: "r", "w", "x", etc. "t" text, "b" binary | ||
</font> | </font> | ||
==Write== | |||
<syntaxhighlight lang='python'> | |||
f = open('/Users/ovidiu/tmp/out.json', 'wt') | |||
f.write("test") | |||
f.close() | |||
</syntaxhighlight> |
Revision as of 20:05, 24 January 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")
f.close()