with
statement PTC-W0010with
statement to open a file125
126 if dist == '':
127 if os.path.exists('/etc/system-release'):
128 release = open('/etc/system-release').read()129 if 'Amazon Linux AMI' in release:
130 dist = 'centos'
131
with
statement to open a file119
120 if dist == '':
121 if os.path.exists('/etc/os-release'):
122 release = open('/etc/os-release').read()123 if 'Arch Linux' in release:
124 dist = 'arch'
125
with
statement to open a file 80 for d in sorted(os.listdir(adapter_dir)):
81 props = {}
82 path = os.path.join(adapter_dir, d, 'state')
83 for l in open(path).read().splitlines(): 84 if ':' in l:
85 key, value = l.strip().split(':')
86 props[key] = value.strip()
with
statement to open a file 47 os.path.join(battery_dir, d, 'info'),
48 os.path.join(battery_dir, d, 'state'),
49 ]:
50 for l in open(path).read().splitlines(): 51 if ':' in l:
52 key, value = l.strip().split(':')
53 props[key] = value.strip()
with
statement to open a file193 target = os.path.join(path, name.replace('/', ''))
194 with open(target, 'wb') as f:
195 for i in range(len(os.listdir(chunk_dir))):
196 f.write(open(os.path.join(chunk_dir, str(i + 1)), 'rb').read())197
198 shutil.rmtree(chunk_dir)
199 targets.append(target)
Opening a file using with
statement is preferred as function open
implements the context manager protocol that releases the resource when it is outside of the with
block. Not doing so requires you to manually release the resource.
f = open('/tmp/.deepsource.toml', 'w')
f.write("config file.")
# No `f.close()` statement: file may remain unaccessible
with open('/tmp/.deepsource.toml', 'w') as f:
f.write("config file.")