with
statement PTC-W0010with
statement to open a file 63fcpp.close()
64
65filenamew = sys.argv[2]
66filetowrite = open(filenamew, 'w') 67filetowrite.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
68filetowrite.write("<results>\n")
69
with
statement to open a file 58 exit()
59
60absfilepath = os.path.abspath(sys.argv[1])
61fcpp = open(os.path.abspath(absfilepath), "r") 62_FILE_LINES = fcpp.readlines()
63fcpp.close()
64
with
statement to open a file130
131# open file for writing
132filenamew = "cpplint.xml"
133filetowrite = open(filenamew, 'w')134filetowrite.write("<?xml version=\"1.0\" encoding=\"ASCII\"?>\n")
135filetowrite.write("<rules>\n")
136
with
statement to open a file124# ## read file into memory for fixing
125absfilepath = os.path.abspath(sys.argv[1])
126# load file into memory
127fcpp = open(os.path.abspath(absfilepath), "r")128_FILE_LINES = fcpp.readlines()
129fcpp.close()
130
with
statement to open a file 29
30def WriteUpdateFile(filename):
31 global _FILE_LINES
32 filetowrite = open(filename, 'w') 33 for linei in _FILE_LINES:
34 if linei.startswith(' if category in _ERROR_CATEGORIES:'):
35 filetowrite.write(' for value in _ERROR_CATEGORIES:\n')
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.")