Skip to content

Commit c230a42

Browse files
dilshodclaude
andcommitted
Fix ResourceWarning by adding context manager support (#301)
- Add context manager support (__enter__/__exit__) to Xlsx2csv class - Add explicit close() method for proper file handle cleanup - Update main usage patterns to use context manager - Prevents ResourceWarning in modern Python versions 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 140c708 commit c230a42

File tree

3 files changed

+33
-9
lines changed

3 files changed

+33
-9
lines changed

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
version 0.8.4 (2025-Oct-1):
22
* Add --continue-on-error option for batch processing to continue when individual files fail
3+
* Fix ResourceWarning by adding context manager support and proper file handle cleanup
34

45
version 0.8.3 (2024-Jul-29):
56
* Fix bug when missing workbook relationship

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@ will output each file in the input directory converted to `.csv` in the output d
9090
Usage from within Python:
9191
```
9292
from xlsx2csv import Xlsx2csv
93+
94+
# Recommended: using context manager for proper resource cleanup
95+
with Xlsx2csv("myfile.xlsx", outputencoding="utf-8") as xlsx2csv:
96+
xlsx2csv.convert("myfile.csv")
97+
98+
# Simple usage (but may cause ResourceWarning in modern Python)
9399
Xlsx2csv("myfile.xlsx", outputencoding="utf-8").convert("myfile.csv")
94100
```
95101

xlsx2csv.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,12 @@ class XlsxValueError(XlsxException):
156156

157157
class Xlsx2csv:
158158
"""
159-
Usage: Xlsx2csv("test.xlsx", **params).convert("test.csv", sheetid=1)
159+
Usage:
160+
with Xlsx2csv("test.xlsx", **params) as xlsx2csv:
161+
xlsx2csv.convert("test.csv", sheetid=1)
162+
163+
Or for simple usage:
164+
Xlsx2csv("test.xlsx", **params).convert("test.csv", sheetid=1)
160165
Input:
161166
xlsxfile - path to file or filehandle
162167
options:
@@ -233,10 +238,21 @@ def __init__(self, xlsxfile, **options):
233238
if self.options['escape_strings']:
234239
self.shared_strings.escape_strings()
235240

241+
def __enter__(self):
242+
return self
243+
244+
def __exit__(self, exc_type, exc_val, exc_tb):
245+
self.close()
246+
236247
def __del__(self):
248+
# Fallback cleanup, but prefer explicit close() or using as context manager
249+
self.close()
250+
251+
def close(self):
252+
"""Explicitly close the underlying zip file handle."""
237253
if self.ziphandle:
238-
# make sure to close zip file
239254
self.ziphandle.close()
255+
self.ziphandle = None
240256

241257
def getSheetIdByName(self, name):
242258
for s in self.workbook.sheets:
@@ -1090,7 +1106,8 @@ def convert_recursive(path, sheetid, outfile, kwargs, continue_on_error=False):
10901106

10911107
print("Converting %s to %s" % (fullpath, outfilepath))
10921108
try:
1093-
Xlsx2csv(fullpath, **kwargs).convert(outfilepath, sheetid)
1109+
with Xlsx2csv(fullpath, **kwargs) as xlsx2csv:
1110+
xlsx2csv.convert(outfilepath, sheetid)
10941111
except Exception as e:
10951112
if continue_on_error:
10961113
print("ERROR processing file '%s': %s" % (fullpath, str(e)), file=sys.stderr)
@@ -1265,12 +1282,12 @@ def main():
12651282
elif not os.path.exists(options.infile) and options.infile != "-":
12661283
raise InvalidXlsxFileException("Input file not found!")
12671284
else:
1268-
xlsx2csv = Xlsx2csv(options.infile, **kwargs)
1269-
if options.sheetname:
1270-
sheetid = xlsx2csv.getSheetIdByName(options.sheetname)
1271-
if not sheetid:
1272-
sys.exit("Sheet '%s' not found" % options.sheetname)
1273-
xlsx2csv.convert(outfile, sheetid)
1285+
with Xlsx2csv(options.infile, **kwargs) as xlsx2csv:
1286+
if options.sheetname:
1287+
sheetid = xlsx2csv.getSheetIdByName(options.sheetname)
1288+
if not sheetid:
1289+
sys.exit("Sheet '%s' not found" % options.sheetname)
1290+
xlsx2csv.convert(outfile, sheetid)
12741291
except XlsxException:
12751292
_, e, _ = sys.exc_info()
12761293
sys.exit(str(e) + "\n")

0 commit comments

Comments
 (0)