File Operations in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
=Reading/Writing from/to Files=
=Reading/Writing from/to Files=
==Read==
==Read==
<font size=-1>
<syntaxhighlight lang='python'>
  f = open(''filename'', ''mode'')
  f = open(''filename'', ''mode'')
  c = f.read()
  c = f.read()
  f.close()
  f.close()
</syntaxhighlight >
<font color=darkkhaki>
Understand this idiom. What does <code>with</code> do? Does it automatically close the file when it exits the block?
<syntaxhighlight lang='python'>
with open('somefile.txt', 'rt') as f:
  text = f.read();
...
</syntaxhighlight >
</font>
</font>
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
Line 37: Line 45:
f.close()
f.close()
</syntaxhighlight>
</syntaxhighlight>
=Working Directory=
=Working Directory=
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>

Revision as of 04:33, 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()

Understand this idiom. What does with do? Does it automatically close the file when it exits the block?

with open('somefile.txt', 'rt') as f:
  text = f.read();
...

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:

os

The Path of the Running Script File

print('__file__:', __file__)

Paths

os.path.basename returns the file name from the file path:

import os
print(os.path.basename(__file__))

os.path.dirname returns the directory name from the file path.

import os
print(os.path.dirname(__file__))

os.path.abspath return the absolute path from a file path.

os.path.splittext returns the file name from the file path.

Use the pathlib module to extract directory name.