Printing is unavailable

This course is licensed for personal online viewing only.

Public preview • CL-P000000-C28-L1281-2C0F9089

Home Dashboard
Chapter 43 · Module 4 — Data Input and Output with NumPy

Saving Arrays to Text and CSV Files

Priority
  • JobHigh
  • InterviewMedium
  • DevelopmentHigh
2,967
words
17
min read
2
tools

1. Learning Outcomes#

या chapter नंतर तुम्हाला:

  • NumPy array ला text-based file मध्ये save करण्यामागचा उद्देश समजेल.
  • np.savetxt() वापरून 1D आणि 2D arrays save करता येतील.
  • CSV file तयार करण्यासाठी delimiter="," योग्य प्रकारे वापरता येईल.
  • fmt वापरून integer आणि floating-point values कशा लिहायच्या ते समजेल.
  • header, comments, आणि basic footer behavior समजेल.
  • .gz extension वापरून compressed text file save करण्याची basic कल्पना येईल.
  • np.loadtxt() वापरून saved data पुन्हा load करता येईल.
  • save झालेला data shape आणि values तपासून validate करता येईल.

2. Text-Based Array Export म्हणजे काय#

NumPy array साधारणपणे program च्या memory मध्ये असतो. Program बंद झाला की तो array आपोआप एखाद्या reusable file मध्ये मिळेलच असे नाही.

कधी आपल्याला array मधील values बाहेर save करायच्या असतात. उदाहरणार्थ:

  • दुसऱ्या program ला data द्यायचा आहे.
  • CSV file Excel किंवा दुसऱ्या data tool मध्ये उघडायची आहे.
  • generated results नंतर पुन्हा वापरायचे आहेत.
  • model किंवा analysis pipeline मधील intermediate numeric data inspect करायचा आहे.

Text-based export मध्ये array मधील numbers साध्या text स्वरूपात file मध्ये लिहिले जातात.

Visual Diagram80%

Rendering diagram…

इथे एक महत्त्वाची गोष्ट लक्षात ठेवा: text file मध्ये values दिसतात, पण NumPy array ची प्रत्येक internal property तशीच्या तशी preserve होईलच असे नाही. त्यामुळे save केल्यानंतर reload आणि validation करणे चांगली सवय आहे.

3. np.savetxt() ची मूलभूत कल्पना#

np.savetxt() हे NumPy function array मधील values text file मध्ये लिहिते.

सर्वात basic pattern:

PYTHON
import numpy as np

data = np.array([10, 20, 30])

np.savetxt("data.txt", data)

या call मध्ये:

  • "data.txt" हे output file चे नाव आहे.
  • data हा save करायचा NumPy array आहे.
  • format किंवा delimiter दिलेला नसल्यामुळे NumPy default text formatting वापरते.

Beginner म्हणून default formatting पाहून घाबरू नका. Floating-point values scientific notation मध्ये दिसू शकतात. Practical कामात आपल्याला file कशी दिसावी हे नियंत्रित करण्यासाठी fmt आणि delimiter वापरणे जास्त उपयुक्त ठरते.

Key Idea

np.savetxt() म्हणजे array मधील values ला human-readable text representation मध्ये file मध्ये लिहिण्याचा सोपा मार्ग.

4. 1D Array Text File मध्ये Save करणे#

आपल्याकडे विद्यार्थ्यांचे scores आहेत:

PYTHON
import numpy as np

scores = np.array([72, 85, 91, 68])

np.savetxt("scores.txt", scores, fmt="%d")

इथे fmt="%d" वापरले आहे कारण values integer स्वरूपात लिहायच्या आहेत.

Saved file मध्ये प्रत्येक value स्वतंत्र line वर दिसेल:

Line File content
1 72
2 85
3 91
4 68

1D array save करताना हा vertical format सुरुवातीला थोडा वेगळा वाटू शकतो. पण प्रत्येक array element एक record म्हणून line वर लिहिला जातो.

5. 2D Array Text File मध्ये Save करणे#

आता rows आणि columns असलेला 2D array पाहू.

PYTHON
import numpy as np

marks = np.array([
    [101, 78, 82],
    [102, 91, 88],
    [103, 74, 79]
])

np.savetxt("marks.txt", marks, fmt="%d")

या file मध्ये तीन rows असतील. प्रत्येक row मधील values default whitespace ने separated असतील.

Row File content
1 101 78 82
2 102 91 88
3 103 74 79

Array मधील row structure text file मध्येही naturally दिसते. त्यामुळे 2D tabular numeric data export करण्यासाठी savetxt() उपयोगी ठरते.

6. CSV File Save करणे#

CSV म्हणजे Comma-Separated Values.

म्हणजे एका row मधील neighboring values comma ने separate केल्या जातात.

त्याच marks array ला CSV मध्ये save करू:

PYTHON
import numpy as np

marks = np.array([
    [101, 78, 82],
    [102, 91, 88],
    [103, 74, 79]
])

np.savetxt(
    "marks.csv",
    marks,
    delimiter=",",
    fmt="%d"
)

आता file content असे दिसेल:

Row File content
1 101,78,82
2 102,91,88
3 103,74,79

इथे मुख्य बदल फक्त delimiter="," हा आहे.

Remember

File extension .csv दिल्यानेच comma separator आपोआप लागू होत नाही. CSV-style separation स्पष्टपणे हवी असेल तर delimiter="," द्या.

7. delimiter Parameter#

delimiter म्हणजे एका value नंतर दुसरी value वेगळी दाखवण्यासाठी कोणता separator वापरायचा ते.

CSV साठी:

PYTHON
np.savetxt("data.csv", data, delimiter=",")

Whitespace-separated text साठी default behavior वापरू शकतो.

Delimiter save करताना आणि load करताना match असणे खूप महत्त्वाचे आहे.

जर file comma-separated असेल, तर reload करताना देखील:

PYTHON
loaded = np.loadtxt("data.csv", delimiter=",")
Common Mistake

CSV comma ने save करून np.loadtxt("data.csv") असे delimiter न देता load केल्यास parsing error येऊ शकतो, कारण np.loadtxt() चा default delimiter whitespace असतो.

8. fmt Parameter — File मधील Number Format Control करणे#

fmt म्हणजे value file मध्ये कोणत्या textual format मध्ये लिहायची ते.

हा parameter दोन practical कारणांसाठी महत्त्वाचा आहे:

  1. file readable बनवणे
  2. decimal precision control करणे

Integer Values लिहिणे#

Integer values साठी:

PYTHON
values = np.array([10, 20, 30, 40])

np.savetxt("integers.txt", values, fmt="%d")

%d मुळे values 10, 20, 30, 40 अशा integer form मध्ये लिहिल्या जातात.

जर floating-point array वर %d वापरला, तर decimal भाग preserve होणार नाही. म्हणून format निवडताना data चा अर्थ लक्षात घ्या.

Floating-Point Values लिहिणे#

Floating-point values दोन decimal places पर्यंत save करायच्या असतील:

PYTHON
temperatures = np.array([36.678, 37.126, 35.994])

np.savetxt(
    "temperatures.txt",
    temperatures,
    fmt="%.2f"
)

Saved values अशा प्रकारे दिसतील:

Original value Saved text
36.678 36.68
37.126 37.13
35.994 35.99

%.2f मधील .2 म्हणजे decimal point नंतर दोन digits.

महत्त्वाचे

fmt फक्त appearance बदलत नाही; कमी precision वापरल्यास information कमी होऊ शकते. उदाहरणार्थ 1.23456 ला %.2f ने save केल्यास file मध्ये 1.23 राहते.

"थेंबे थेंबे तळे साचे" तसेच decimal precision मध्ये छोटे differences अनेक values मध्ये जमा होऊ शकतात. त्यामुळे data analysis मध्ये precision विचारपूर्वक निवडा.

9. Column Headings साठी header#

CSV file मध्ये columns चा अर्थ कळण्यासाठी heading उपयोगी पडते.

PYTHON
import numpy as np

marks = np.array([
    [101, 78, 82],
    [102, 91, 88],
    [103, 74, 79]
])

np.savetxt(
    "marks.csv",
    marks,
    delimiter=",",
    fmt="%d",
    header="StudentID,Math,Science"
)

Default behavior मध्ये header च्या आधी # prefix येतो.

File च्या सुरुवातीची line अशी दिसेल:

# StudentID,Math,Science

त्यानंतर numeric rows येतील.

हे NumPy साठी उपयोगी behavior आहे, कारण np.loadtxt() default ने # ने सुरू होणाऱ्या text ला comment मानते. त्यामुळे असा header data म्हणून parse करण्याचा प्रयत्न होत नाही.

10. comments Prefix समजून घेणे#

np.savetxt() मध्ये comments चा default value "# " असतो.

म्हणून:

PYTHON
np.savetxt(
    "marks.csv",
    marks,
    delimiter=",",
    fmt="%d",
    header="StudentID,Math,Science"
)

या header च्या आधी # येतो.

काही external tools साठी plain CSV heading हवी असेल तर:

PYTHON
np.savetxt(
    "marks.csv",
    marks,
    delimiter=",",
    fmt="%d",
    header="StudentID,Math,Science",
    comments=""
)

आता पहिली line अशी असेल:

StudentID,Math,Science

पण इथे एक trade-off आहे. ही line आता comment नाही. त्यामुळे np.loadtxt() वापरताना पहिली row skip करावी लागते:

PYTHON
loaded = np.loadtxt(
    "marks.csv",
    delimiter=",",
    dtype=int,
    skiprows=1
)
Key Idea

Default comments="# " NumPy reload साठी convenient आहे. comments="" human-friendly plain CSV header देऊ शकते, पण load करताना header manually skip करावा लागू शकतो.

footer वापरून file च्या शेवटी informational text जोडता येते.

PYTHON
np.savetxt(
    "marks.txt",
    marks,
    fmt="%d",
    footer="End of marks data"
)

Default comments="# " असल्यामुळे footer देखील comment form मध्ये लिहिला जातो.

Footer numeric dataset चा भाग नसतो. तो file बद्दल छोटा note देण्यासाठी वापरता येतो.

Beginner level वर एवढे लक्षात ठेवा: header वर माहिती देतो, footer शेवटी माहिती देतो, आणि default comments prefix मुळे दोन्ही numeric parsing पासून वेगळे राहू शकतात.

12. .gz Compressed Text File Save करणे#

Numeric text data मोठा झाला तर compression उपयोगी ठरू शकते.

Filename .gz ने संपत असेल तर np.savetxt() gzip-compressed text लिहू शकते.

PYTHON
import numpy as np

data = np.array([
    [10.5, 20.25],
    [30.75, 40.0]
])

np.savetxt(
    "data.csv.gz",
    data,
    delimiter=",",
    fmt="%.2f"
)

हा अजूनही text-based numeric export आहे, पण file gzip compression मध्ये store होते.

पुन्हा load करताना:

PYTHON
loaded = np.loadtxt(
    "data.csv.gz",
    delimiter=","
)

Basic use case मध्ये NumPy compressed filename handle करू शकते.

Note

Compression storage कमी करण्यासाठी उपयोगी असू शकते. पण file manually उघडून text पाहायचा असेल तर normal .txt किंवा .csv अधिक convenient वाटू शकते.

13. Saved Data पुन्हा np.loadtxt() ने Load करणे#

Save करणे हा flow चा अर्धा भाग आहे. दुसरा महत्त्वाचा भाग म्हणजे data पुन्हा योग्य प्रकारे मिळतो का ते तपासणे.

Integer CSV Reload#

PYTHON
import numpy as np

marks = np.array([
    [101, 78, 82],
    [102, 91, 88],
    [103, 74, 79]
])

np.savetxt(
    "marks.csv",
    marks,
    delimiter=",",
    fmt="%d"
)

loaded_marks = np.loadtxt(
    "marks.csv",
    delimiter=",",
    dtype=int
)

इथे dtype=int दिल्यामुळे loaded array integer type मध्ये मिळतो.

जर dtype दिला नाही, तर np.loadtxt() सामान्य numeric loading मध्ये floating-point array देऊ शकते. त्यामुळे saved text visually integer असला तरी loaded dtype तसाच राहील असे assume करू नका.

14. Save आणि Reload केलेला Data Validate करणे#

Reliable workflow असा आहे:

save → reload → compare

फक्त file तयार झाली म्हणजे काम पूर्ण असे मानू नका.

Shape Check#

पहिले shape compare करा:

PYTHON
same_shape = original.shape == loaded.shape

यामुळे rows/columns ची basic structure match होते का ते कळते.

Value Check#

Floating-point values साठी:

PYTHON
same_values = np.allclose(original, loaded)

np.allclose() corresponding numeric values जवळपास समान आहेत का ते तपासते.

हे floating-point data साठी practical आहे, कारण text formatting मुळे छोटा rounding difference येऊ शकतो.

Complete Validation Example#

PYTHON
import numpy as np

original = np.array([
    [12.345, 67.890],
    [45.678, 90.123]
])

np.savetxt(
    "measurements.csv",
    original,
    delimiter=",",
    fmt="%.3f"
)

loaded = np.loadtxt(
    "measurements.csv",
    delimiter=","
)

same_shape = original.shape == loaded.shape
same_values = np.allclose(original, loaded)

print(same_shape)
print(same_values)

या example मध्ये original values आधीच तीन decimal places पर्यंत आहेत आणि त्याच precision ने save केल्या आहेत. त्यामुळे shape आणि values दोन्ही match होतात.

जर तुम्ही fmt="%.1f" सारखी कमी precision वापरली, तर loaded values rounded असतील. अशा वेळी exact original values परत मिळतीलच असे नाही.

Remember

Text export मध्ये fmt हा फक्त display decision नाही. तो round-trip data quality वर परिणाम करू शकतो.

15. Practical CSV Workflow#

एका simple numeric reporting workflow मध्ये खालील pattern उपयोगी पडतो:

PYTHON
import numpy as np

monthly_sales = np.array([
    [120.50, 140.75, 160.25],
    [98.25, 110.50, 130.00],
    [210.00, 225.40, 240.80]
])

np.savetxt(
    "monthly_sales.csv",
    monthly_sales,
    delimiter=",",
    fmt="%.2f",
    header="Jan,Feb,Mar"
)

reloaded_sales = np.loadtxt(
    "monthly_sales.csv",
    delimiter=","
)

print(np.allclose(monthly_sales, reloaded_sales))

इथे flow असा आहे:

  1. numeric 2D array तयार आहे.
  2. CSV मध्ये comma separator वापरला.
  3. currency-like values साठी दोन decimal places वापरल्या.
  4. header जोडला.
  5. file पुन्हा त्याच delimiter ने load केली.
  6. values np.allclose() ने validate केल्या.

हा छोटा pattern अनेक data-export tasks साठी मजबूत mental model देतो.

16. Common Mistakes#

Save आणि Load Delimiter वेगळा ठेवणे#

CSV save करताना delimiter="," वापरला, पण load करताना तो विसरलात तर parsing fail होऊ शकते.

योग्य pattern:

PYTHON
np.savetxt("data.csv", data, delimiter=",")
loaded = np.loadtxt("data.csv", delimiter=",")

Precision खूप कमी ठेवणे#

fmt="%.1f" वापरल्यास अनेक decimal values round होतात.

उदाहरणार्थ 12.345 file मध्ये 12.3 होऊ शकते.

जर exact किंवा higher-precision analysis आवश्यक असेल, तर appropriate precision निवडा.

Plain Header असूनही skiprows न वापरणे#

comments="" वापरल्यावर header plain text होते.

अशा file ला numeric np.loadtxt() ने load करताना:

PYTHON
loaded = np.loadtxt(
    "data.csv",
    delimiter=",",
    skiprows=1
)

हा pattern लक्षात ठेवा.

Saved Type आपोआप Preserve होईल असे समजणे#

Text file मध्ये 10 लिहिलेले दिसले तरी load करताना default result floating-point असू शकतो.

Integer result आवश्यक असेल तर योग्य dtype द्या.

Validation न करणे#

File तयार झाली म्हणजे data योग्य save झाला असे निश्चित होत नाही.

कमीतकमी हे दोन checks उपयोगी आहेत:

PYTHON
same_shape = original.shape == loaded.shape
same_values = np.allclose(original, loaded)

17. Interview Preparation#

What is the purpose of np.savetxt() in NumPy?Show Answer

np.savetxt() writes a one-dimensional or two-dimensional NumPy array to a text-based file. It supports configurable delimiters, numeric formatting, headers, footers, and compressed text output through filenames such as .gz.

Key Points:

  • Used for text and CSV-style numeric export.
  • delimiter controls separation between values.
  • fmt controls textual numeric formatting.
  • Text export should be validated when precision matters.

Why interviewer asks this:

It checks whether you understand practical NumPy data export instead of working only with arrays in memory.


Why should the same delimiter be used with np.savetxt() and np.loadtxt()?Show Answer

The delimiter defines how values are separated in the text file. The loader must interpret the file using the same separation rule. If a comma-separated file is loaded with the default whitespace delimiter, parsing can fail.

Key Points:

  • Save format and load format must agree.
  • CSV commonly uses delimiter=",".
  • Header handling must also be considered when reloading.

Why interviewer asks this:

It tests whether you understand the full save-and-reload workflow and common file parsing failures.

18. Recap#

या chapter मधून हे मुख्य points लक्षात ठेवा:

  • np.savetxt() array values text file मध्ये लिहिते.
  • 1D आणि 2D numeric arrays text-based format मध्ये save करता येतात.
  • CSV साठी delimiter="," वापरणे महत्त्वाचे आहे.
  • Integer text साठी fmt="%d" उपयुक्त आहे.
  • Decimal precision साठी fmt="%.2f", fmt="%.3f" अशा formats वापरता येतात.
  • header column information देऊ शकतो.
  • Default comments="# " मुळे header/footer comment lines बनतात.
  • comments="" वापरल्यास plain header मिळतो; reload करताना skiprows लागू शकतो.
  • .gz filename compressed text export साठी वापरता येतो.
  • np.loadtxt() ने data पुन्हा load करताना delimiter आणि dtype लक्षात घ्या.
  • Reliable workflow म्हणजे save → reload → shape check → value check.
  • Floating-point round-trip validation साठी np.allclose() उपयोगी आहे.
Interactive learning

Practice lab

Apply this chapter with guided activities, immediate feedback, explanations, and retry.

Practice loads when this section enters view.