Skip to content

Commit

Permalink
Add section method to MultiCSVFile
Browse files Browse the repository at this point in the history
  • Loading branch information
Donaim committed Aug 7, 2024
1 parent b4019c1 commit 041ef05
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/multicsv/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import TextIO, Optional, Type, List, MutableMapping, Iterator
import shutil
import os
import io
from .subtextio import SubTextIO
from .exceptions import OpOnClosedCSVFileError, CSVFileBaseIOClosed, \
SectionNotFound
Expand Down Expand Up @@ -121,6 +122,7 @@ def __getitem__(self, key: str) -> TextIO:

for item in self._sections:
if item.name == key:
item.descriptor.seek(0)
return item.descriptor

raise SectionNotFound("MultiCSVFile does not "
Expand Down Expand Up @@ -174,6 +176,12 @@ def __contains__(self, key: object) -> bool:

return False

def section(self, name: str) -> TextIO:
if name not in self:
self[name] = io.StringIO("")

return self[name]

def close(self) -> None:
if not self._closed:
try:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ def test_write_csv(example_file):
assert ['section1', 'section2'] == all_sections


def test_write_csv_easier(example_file):
with multicsv.open(example_file, mode='w+') as csv_file:
# Write the CSV content to the file
csv_file.section('section1').write("header1,header2,header3\nvalue1,value2,value3\n")
csv_file.section('section2').write("header4,header5,header6\nvalue4,value5,value6\n")

# Read a section using the csv module
csv_reader = csv.reader(csv_file['section1'])
assert list(csv_reader) == [['header1', 'header2', 'header3'],
['value1', 'value2', 'value3']]

# Get all sections:
all_sections = list(csv_file)
assert ['section1', 'section2'] == all_sections


def test_open_csv():
# Initialize the MultiCSVFile with a base CSV string
csv_content = io.StringIO("[section1]\na,b,c\n1,2,3\n[section2]\nd,e,f\n4,5,6\n")
Expand Down

0 comments on commit 041ef05

Please sign in to comment.