Python
Python_EX-004. 10 way data read from a file
X25WLK
2025. 1. 21. 10:54
No. | Method | Code Example | Pros | Cons |
1 | read() | # to read the entire file with open('filename.txt', 'r') as file: data = file.read() print(data) |
- Simple - Easy to use |
- Not suitable for large files (memory-intensive) |
2 | readline() | # to read one line at a time with open('filename.txt', 'r') as file: line = file.readline() while line: print(line.strip()) line = file.readline() |
- Suitable for large files - Allows processing line-by-line |
- Slightly complex - Requires handling end-of-file manually |
3 | readlines() |
# to read all lines into a list with open('filename.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip()) |
- Easy to use - Stores all lines in a list |
- Not suitable for large files (memory-intensive) |
4 | for loop | # to read line by line with open('filename.txt', 'r') as file: for line in file: print(line.strip()) |
- Simple & clean code - Suitable for large files |
- Slightly less intuitive for beginners |
5 | seek() |
# to read specific parts with open('filename.txt', 'r') as file: file.seek(10) data = file.read(20) print(data) |
- Allows random access to specific parts of the file - Useful for binary files |
- Requires knowledge of file structure - More complex code |
6 | Reading a file | # reading a file # as a list comprehension with open('filename.txt', 'r') as file: lines = [line.strip() for line in file] print(lines) |
- Concise & expressive code - Combines reading & processing |
- Not suitable for large files (memory-intensive) |
7 | Path from pathlib |
# Path from pathlib from pathlib import Path data = Path('filename.txt').read_text() print(data) |
- Modern & user-friendly API - Integrates well with other pathlib functionalities |
- Requires pathlib (Python 3.4+) - Limited to text files |
8 | numpy |
# to read data # (for structured data) import numpy as np data = np.loadtxt('filename.txt') print(data) |
- Efficient for numerical data - Provides powerful data manipulation capabilities |
- Requires numpy library - Suitable mainly for numerical data |
9 | pandas: | # to read data # (for tabular data) pimport pandas as pd df = pd.read_csv('filename.txt') print(df) |
- Excellent for tabular data - Provides powerful data analysis tools |
Requires pandas library - More complex than basic file reading |
10 | csv module |
# to read CSV files import csv with open('filename.txt', 'r') as file: reader = csv.reader(file) for row in reader: print(row) |
- Built-in module (no additional installation required) - Suitable for CSV files |
- Limited to CSV files - Requires handling of CSV-specific issues (e.g., delimiters, quoting) |
반응형