String से File-like Object बनाना
String के Contents के साथ File-like Object (File जैसा Duck Type) बनाने के लिए, आप StringIO Module का उपयोग कर सकते हैं। अपने String को StringIO के Constructor में Pass करें और फिर आप इसे File Like Object की तरह उपयोग कर सकते हैं।
Python 2:
>>> from cStringIO import StringIO
>>> f = StringIO('Hello world')
>>> f.read()
'Hello world'
Python 3 (io Module):
>>> import io
>>> f = io.StringIO('Hello world')
>>> f.read()
'Hello world'
Note: StringIO Unicode Strings को Accept नहीं करता जिन्हें Plain ASCII Strings के रूप में Encode नहीं किया जा सकता।
Bytes के लिए: BytesIO
>>> import io >>> f = io.BytesIO(b'Hello world') >>> f.read() b'Hello world'
Complete Example with File Operations:
import io
# StringIO - Text Mode
text_buffer = io.StringIO()
text_buffer.write('Hello, ')
text_buffer.write('World!')
text_buffer.seek(0) # Beginning पर वापस जाएं
print(text_buffer.read()) # 'Hello, World!'
# BytesIO - Binary Mode
binary_buffer = io.BytesIO()
binary_buffer.write(b'Binary data')
binary_buffer.seek(0)
print(binary_buffer.read()) # b'Binary data'
# Context Manager के साथ
with io.StringIO('Initial content') as f:
print(f.read())
f.write('More content')
f.seek(0)
print(f.read())
Use Cases:
- Testing में Real Files के बजाय
- Memory में Large Strings Build करना
- String Data को File-expecting APIs को Pass करना
- Compression Libraries (gzip, zlib) के साथ