एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना
एजेंट टूल से open(), pathlib.Path और CSV/JSON/TXT फ़ाइलें पढ़ना।
एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना, CoddyKit पर AI एजेंट का एक निःशुल्क पाठ है। यह 4 में से 1वाँ पाठ है। आप नीचे पूरा पाठ निःशुल्क पढ़ सकते हैं—फिर अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर के साथ ब्राउज़र में इसका व्यावहारिक अभ्यास कर सकते हैं। यह AI एजेंट सीखने के मार्ग का हिस्सा है और आपकी प्रगति वेब तथा CoddyKit ऐप पर सिंक होती रहती है। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।
एजेंटों के लिए फ़ाइल इनपुट/आउटपुट क्यों महत्वपूर्ण है
एजेंटों को अक्सर कॉन्फ़िगरेशन पढ़ने, मध्यवर्ती परिणाम संग्रहीत करने और आउटपुट रिपोर्ट लिखने की आवश्यकता होती है। Python फ़ाइलों के साथ काम करने के दो प्रमुख तरीके देता है: अंतर्निहित open() फ़ंक्शन और आधुनिक pathlib मॉड्यूल। दोनों की जानकारी होना आवश्यक है।
हर फ़ाइल संचालन में यह सुनिश्चित करने के लिए संदर्भ प्रबंधक (with कथन) का उपयोग करें कि कोई त्रुटि होने पर भी फ़ाइल बंद हो जाए।
with open('config.txt', 'w', encoding='utf-8') as f:
f.write('model=gpt-4o-mini\nmax_steps=20\n')
with open('config.txt', 'r', encoding='utf-8') as f:
content = f.read()
from pathlib import Path
content = Path('config.txt').read_text(encoding='utf-8')
print(content)open() से फ़ाइलें पढ़ना
open() फ़ंक्शन फ़ाइल नाम और एक मोड लेता है। पाठ पढ़ने के लिए 'r' मोड का उपयोग करें। आप पूरी फ़ाइल को एक बार में .read() से, पंक्ति-दर-पंक्ति .readline() से या सभी पंक्तियों को सूची में .readlines() से पढ़ सकते हैं।
प्लैटफ़ॉर्म-विशिष्ट एन्कोडिंग से जुड़ी अनपेक्षित समस्याओं से बचने के लिए हमेशा encoding='utf-8' निर्दिष्ट करें।
with open('report.txt', 'w', encoding='utf-8') as f:
f.write('Quarterly agent report body text.')
with open('large_log.txt', 'w', encoding='utf-8') as f:
f.write('INFO: started\nERROR: timeout\nINFO: done\n')
with open('tasks.txt', 'w', encoding='utf-8') as f:
f.write('task one\ntask two\n')
with open('report.txt', 'r', encoding='utf-8') as f:
full_text = f.read()
print(f'Read {len(full_text)} characters')
with open('large_log.txt', 'r', encoding='utf-8') as f:
for line in f:
line = line.rstrip('\n')
if 'ERROR' in line:
print('Found error:', line)
with open('tasks.txt', 'r', encoding='utf-8') as f:
tasks = f.readlines()
tasks = [t.strip() for t in tasks]
print('Tasks:', tasks)open() से फ़ाइलों में लिखना
लिखने के लिए 'w' मोड (बनाता या अधिलेखित करता है), जोड़ने के लिए 'a' मोड और केवल नई फ़ाइल बनाने के लिए 'x' मोड का उपयोग करें (यदि फ़ाइल पहले से मौजूद हो तो यह विफल हो जाता है)। 'w' मोड पहले फ़ाइल की मौजूदा सामग्री मिटा देता है—इसलिए पहले से मौजूद डेटा के साथ सावधान रहें।
# Write a new file (or overwrite)
results = ['Task 1 complete', 'Task 2 complete', 'Task 3 failed']
with open('results.txt', 'w', encoding='utf-8') as f:
for result in results:
f.write(result + '\n')
# Append to existing file (add without overwriting)
with open('agent_log.txt', 'a', encoding='utf-8') as f:
f.write('2026-05-29 14:30: Agent completed batch\n')
# Create exclusively — error if file already exists
try:
with open('unique_report.txt', 'x', encoding='utf-8') as f:
f.write('This file is new')
except FileExistsError:
print('File already exists, skipping')
# --- demo ---
print('results.txt contents:')
with open('results.txt', encoding='utf-8') as f:
print(f.read())
# Try the exclusive create again now that the file exists
try:
with open('unique_report.txt', 'x', encoding='utf-8') as f:
f.write('This file is new')
except FileExistsError:
print('File already exists, skipping')
pathlib.Path — आधुनिक फ़ाइल संचालन
pathlib.Path फ़ाइल पथों के लिए ऑब्जेक्ट-आधारित तरीका प्रदान करता है। यह os.path की तुलना में अधिक पठनीय है और विभिन्न प्लेटफ़ॉर्म के पथ-विभाजकों को अपने-आप संभालता है। सरल पढ़ने-लिखने के कार्यों के लिए read_text() और write_text() सबसे साफ़ तरीका हैं।
from pathlib import Path
base = Path('agent_workspace')
base.mkdir(exist_ok=True)
config_file = base / 'config.json'
config_file.write_text('{"model": "gpt-4o-mini"}', encoding='utf-8')
if config_file.exists():
content = config_file.read_text(encoding='utf-8')
print('Config:', content)
output = base / 'output' / 'report.txt'
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text('Agent report\nLine 2', encoding='utf-8')
Path('image.png').write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(100)))
binary_data = Path('image.png').read_bytes()
print(f'File size: {len(binary_data)} bytes')JSON फ़ाइलें पढ़ना और लिखना
एजेंट अक्सर संरचित डेटा का आदान-प्रदान JSON फ़ाइलों के रूप में करते हैं। JSON फ़ाइल को पार्स करने के लिए json.load() और उसे लिखने के लिए json.dump() का उपयोग करें। मनुष्यों के लिए पठनीय आउटपुट के लिए हमेशा indent=2 का उपयोग करें और Unicode वर्णों को सुरक्षित रखने के लिए ensure_ascii=False रखें।
import json
from pathlib import Path
config_path = Path('agent_config.json')
config_path.write_text(json.dumps({'max_retries': 5, 'model': 'gpt-4o-mini'}), encoding='utf-8')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
print('Max retries:', config.get('max_retries', 3))
print('Model:', config.get('model', 'gpt-4o-mini'))
results = {
'run_id': 'run-001',
'status': 'completed',
'items_processed': 142,
'errors': []
}
with open('results.json', 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print('Results written to results.json')Context Managers — सही तरीका
with कथन (context manager) यह सुनिश्चित करता है कि ब्लॉक समाप्त होने पर फ़ाइल बंद हो जाए — भले ही पढ़ने के बीच में कोई अपवाद उत्पन्न हो। इसके बिना फ़ाइलें खुली रह सकती हैं और फ़ाइल डिस्क्रिप्टर समाप्त हो सकते हैं, जिससे फ़ाइल हैंडल की सीमा वाले सिस्टम पर क्रैश हो सकता है।
with open('data.txt', 'w', encoding='utf-8') as f:
f.write('sample content')
f = open('data.txt', 'r')
try:
content = f.read()
finally:
f.close()
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
with open('input.txt', 'w', encoding='utf-8') as f:
f.write('hello\nworld\n')
with open('input.txt', 'r') as infile, \
open('output.txt', 'w') as outfile:
for line in infile:
processed = line.upper()
outfile.write(processed)
print('Done:', content)बाइनरी फ़ाइलों के साथ काम करना
बाइनरी फ़ाइलों (चित्रों, PDF और ऑडियो) को पढ़ने के लिए मोड 'rb' और उन्हें लिखने के लिए 'wb' का उपयोग करें। बाइनरी सामग्री को कभी भी पाठ के रूप में डीकोड करने का प्रयास न करें — pathlib के साथ read_bytes()/write_bytes() या open() के साथ बाइनरी मोड का उपयोग करें।
from pathlib import Path
import base64
image_path = Path('screenshot.png')
image_path.write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(50)))
image_bytes = image_path.read_bytes()
print(f'Image size: {len(image_bytes)} bytes')
image_b64 = base64.b64encode(image_bytes).decode('utf-8')
print(f'Base64 length: {len(image_b64)}')
response_bytes = b'...binary content from API...'
output_path = Path('output') / 'generated_image.png'
output_path.parent.mkdir(exist_ok=True)
output_path.write_bytes(response_bytes)
print('Wrote', output_path)एन्कोडिंग और नई पंक्ति से जुड़ी समस्याएँ संभालना
अलग-अलग सिस्टम अलग-अलग नई पंक्ति वाले वर्णों का उपयोग करते हैं (Linux/macOS पर \n, Windows पर \r\n)। हमेशा encoding='utf-8' स्पष्ट रूप से दें और Python को newline=None (डिफ़ॉल्ट) के साथ नई पंक्तियाँ संभालने दें। BOM (बाइट क्रम चिह्न) वाली फ़ाइलों के लिए encoding='utf-8-sig' का उपयोग करें।
with open('data.txt', 'w', encoding='utf-8') as f:
f.write('hello world')
with open('windows_export.csv', 'wb') as f:
f.write('name,email\n'.encode('utf-8'))
with open('unknown_encoding.txt', 'wb') as f:
f.write('cafe resume'.encode('latin-1'))
with open('data.txt', 'r', encoding='utf-8') as f:
text = f.read()
with open('windows_export.csv', 'r', encoding='utf-8-sig') as f:
content = f.read()
try:
with open('unknown_encoding.txt', 'r', encoding='utf-8') as f:
text = f.read()
except UnicodeDecodeError:
with open('unknown_encoding.txt', 'r',
encoding='utf-8', errors='replace') as f:
text = f.read()
print('Warning: file had encoding errors (replaced with ?)')
print('All reads completed. csv content:', repr(content))पंक्ति-दर-पंक्ति कुशल प्रसंस्करण
बड़ी फ़ाइलों (लॉग फ़ाइलों और डेटासेट) के लिए .read() से सब कुछ स्मृति में लाने से बचें। फ़ाइल ऑब्जेक्ट पर सीधे पुनरावृति करें — Python एक बार में एक पंक्ति पढ़ता है, इसलिए फ़ाइल के आकार की परवाह किए बिना स्मृति का उपयोग स्थिर रहता है।
from pathlib import Path
def process_large_log(log_path):
error_count = 0
processed = 0
with open(log_path, 'r', encoding='utf-8') as f:
for line in f: # reads one line at a time
line = line.strip()
if not line:
continue
processed += 1
if '[ERROR]' in line:
error_count += 1
# Process error immediately without storing all lines
handle_error(line)
print(f'Processed {processed} lines, {error_count} errors')
def handle_error(line):
print(f'Error found: {line[:80]}')
# --- demo ---
with open('demo_agent.log', 'w', encoding='utf-8') as f:
f.write('[INFO] agent started\n')
f.write('[ERROR] timeout calling tool search_web\n')
f.write('[INFO] retrying\n')
f.write('[ERROR] tool search_web failed again\n')
process_large_log('demo_agent.log')
निर्देशिकाएँ बनाना और प्रबंधित करना
फ़ाइलें लिखने से पहले सुनिश्चित करें कि मूल निर्देशिका मौजूद है। पहले से मौजूद निर्देशिकाओं पर त्रुटि के बिना नेस्टेड निर्देशिकाएँ बनाने के लिए Path.mkdir(parents=True, exist_ok=True) का उपयोग करें। आउटपुट फ़ाइलें बनाने वाले किसी भी एजेंट की शुरुआत में यह एक सामान्य सेटअप चरण है।
from pathlib import Path
import datetime
# Create output directory structure
today = datetime.date.today().isoformat() # '2026-05-29'
output_dir = Path('agent_output') / today / 'reports'
output_dir.mkdir(parents=True, exist_ok=True)
print(f'Output directory: {output_dir}')
# Now write files safely
for i in range(3):
report_path = output_dir / f'report_{i:02d}.json'
report_path.write_text(
'{"status": "ok"}',
encoding='utf-8'
)
# List all created files
for f in output_dir.iterdir():
print(f' {f.name}: {f.stat().st_size} bytes')एजेंटों के लिए फ़ाइल पथ की सर्वोत्तम प्रथाएँ
एजेंटों को पूर्ण पथों या अच्छी तरह से निर्धारित आधार निर्देशिका के सापेक्ष पथों का उपयोग करना चाहिए। वर्तमान कार्यशील निर्देशिका (./) पर कभी निर्भर न रहें, क्योंकि एजेंट अक्सर अलग-अलग स्थानों से शुरू किए जाते हैं। आधार के रूप में स्क्रिप्ट की निर्देशिका प्राप्त करने के लिए Path(__file__).parent का उपयोग करें।
from pathlib import Path
# Get absolute path relative to THIS script's location
SCRIPT_DIR = Path(__file__).parent
DATA_DIR = SCRIPT_DIR / 'data'
OUTPUT_DIR = SCRIPT_DIR / 'output'
# Always resolve to absolute path before use
config = DATA_DIR / 'config.json'
print('Config path:', config.resolve())
# Check if file exists before reading
if config.exists():
import json
with open(config, 'r', encoding='utf-8') as f:
settings = json.load(f)
else:
print(f'Config not found at {config.resolve()}')
settings = {}
# Safe output path
result_path = (OUTPUT_DIR / 'result.json').resolve()
print('Will write to:', result_path)त्वरित जाँच: Context Managers
फ़ाइल इनपुट/आउटपुट की सर्वोत्तम प्रथाओं की अपनी समझ जाँचें।
फ़ाइल इनपुट/आउटपुट का पुनरावलोकन
अब आपके पास एजेंट कोड में फ़ाइल संचालन की ठोस बुनियाद है:
- पढ़ने के लिए
open('file', 'r', encoding='utf-8'), लिखने के लिए'w'और जोड़ने के लिए'a'का उपयोग करें - फ़ाइलों के बंद होने की गारंटी के लिए हमेशा with कथन का उपयोग करें
- pathlib.Path
read_text()/write_text()के साथ साफ़ और विभिन्न प्लेटफ़ॉर्म पर काम करने वाला पथ प्रबंधन प्रदान करता है - संरचित डेटा के लिए
json.load(f)/json.dump(data, f, indent=2)का उपयोग करें - स्मृति का उपयोग कम रखने के लिए बड़ी फ़ाइलों पर पंक्ति-दर-पंक्ति पुनरावृति करें
- अपनी आधार निर्देशिका के रूप में
Path(__file__).parentका उपयोग करें — cwd पर कभी निर्भर न रहें
एआई शिक्षक के साथ AI एजेंट सीखें — निःशुल्क
अपने ब्राउज़र में वास्तविक कोड लिखें और चलाएँ, चौबीसों घंटे एआई शिक्षक से तुरंत सहायता पाएँ, और वेब या ऐप पर वहीं से शुरू करें जहाँ आपने छोड़ा था।
- पाठ्यक्रम
- 60
- पाठ
- 239
अक्सर पूछे जाने वाले प्रश्न
क्या “एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना” पाठ निःशुल्क है?
हाँ—“एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना” का पूरा पाठ यहाँ वेब पर निःशुल्क पढ़ा जा सकता है। इंटरैक्टिव अभ्यास (अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर) करने और AI एजेंट पाठ्यक्रम का बाकी हिस्सा अनलॉक करने के लिए CoddyKit PRO लें। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।
“एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना” में मैं क्या सीखूँगा?
एजेंट टूल से open(), pathlib.Path और CSV/JSON/TXT फ़ाइलें पढ़ना। आप ब्राउज़र में सीधे चलाए जाने वाले व्यावहारिक कोड के साथ AI एजेंट का अभ्यास करते हैं, और पाठ पूरा करते समय 24/7 एआई ट्यूटर आपके प्रश्नों के उत्तर देता है।
क्या AI एजेंट शुरू करने के लिए मुझे किसी अनुभव की आवश्यकता है?
पहले के अनुभव की आवश्यकता नहीं है। CoddyKit पर AI एजेंट शुरुआती से लेकर उन्नत शिक्षार्थियों तक सभी के लिए व्यवस्थित किया गया है, इसलिए आप यहीं से या शुरुआत से सीखना शुरू कर सकते हैं और अपनी गति से आगे बढ़ सकते हैं। यह 4 में से 1वाँ पाठ है।
“एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना” पाठ पूरा करने में कितना समय लगता है?
CoddyKit का अधिकांश पाठ लगभग 5–10 मिनट में पूरा हो जाता है। हर पाठ छोटा और संवादात्मक है, इसलिए आप लगातार प्रगति करते हैं और वेब या ऐप पर वहीं से सीखना जारी रख सकते हैं जहाँ आपने छोड़ा था।
क्या मैं इस AI एजेंट पाठ में कोड लिख और चला सकता हूँ?
हाँ। हर AI एजेंट पाठ में एक अंतर्निर्मित कोड संपादक शामिल है, जिससे आप सीधे अपने ब्राउज़र में वास्तविक कोड लिख और चला सकते हैं और तुरंत एआई प्रतिक्रिया पा सकते हैं—स्थानीय सेटअप की आवश्यकता नहीं है।
इस पाठ्यक्रम के सभी पाठ
- एजेंट संदर्भ में फ़ाइलें पढ़ना और लिखना
- निर्देशिका भ्रमण और फ़ाइल खोज
- फ़ाइल प्रारूप संभालना: CSV, JSON और TXT
- त्रुटि-संभाल के साथ सुरक्षित फ़ाइल संचालन