Refactor file opening

This commit is contained in:
Morgan Courbet 2017-07-09 11:10:10 +02:00
parent d16d04a4d7
commit 8bc4af45ba
No known key found for this signature in database
GPG key ID: 467299D324A21B24

View file

@ -129,9 +129,8 @@ def _check_filenames(filenames):
def _detect_line_ending(filename): def _detect_line_ending(filename):
f = open(filename, 'rb') with open(filename, 'rb') as f:
buf = f.read() buf = f.read()
f.close()
crlf_nb = len(LineEnding.CRLF.regex.findall(buf)) crlf_nb = len(LineEnding.CRLF.regex.findall(buf))
lf_nb = len(LineEnding.LF.regex.findall(buf)) lf_nb = len(LineEnding.LF.regex.findall(buf))
@ -222,17 +221,16 @@ def _process_fix_force(filenames, line_ending_enum):
def _convert_line_ending(filename, line_ending): def _convert_line_ending(filename, line_ending):
# read the file # read the file
fin = open(filename, 'rb') with open(filename, 'rb+') as f:
bufin = fin.read() bufin = f.read()
fin.close()
# convert line ending # convert line ending
bufout = ANY_LINE_ENDING_PATTERN.sub(line_ending, bufin) bufout = ANY_LINE_ENDING_PATTERN.sub(line_ending, bufin)
# write the result in the file # write the result in the file
fout = open(filename, 'wb') f.seek(0)
fout.write(bufout) f.write(bufout)
fout.close() f.truncate()
if __name__ == '__main__': if __name__ == '__main__':