나는 떡갈나무가 될 거야 나는 신갈나무가 될 거야 나는 상수리나무가 될 거야 아름드리나무가 되어서 다람쥐들에게 도토리를 두루 나눠 줄 거야
그래그래 우리 나중에 다람쥐들한테 도토리 많이 나눠주자
- 최승호의 시집 《부처님의 작은 선물》 에 실린 시 〈도토리〉 중에서 -
* 저희 옹달샘에도 도토리나무가 많습니다. 떡갈나무, 신갈나무, 상수리나무, 이파리 모양에 따라 이름이 다르지만 모두 도토리나무로 통합니다. 도토리 떡잎에 다람쥐의 생존이 달려 있습니다. 떡잎이 튼실할수록 큰 나무로 자라 더 많은 도토리가 열리고, 더 많은 다람쥐들이 그 혜택을 누릴 것입니다. 그것이 자연의 순리입니다.
import requests
response = requests.get('https://api.example.com/data')
try:
response.raise_for_status() # Raises an HTTPError if the status is 4xx, 5xx
data = response.json()
print(data)
except requests.exceptions.HTTPError as err:
print(f'HTTP Error: {err}')
4. Setting Timeout for Requests
To set a timeout for API requests to avoid hanging indefinitely:
import requests
response = requests.get('https://api.example.com/data')
response.encoding = 'utf-8' # Set encoding to match the expected response format
data = response.text
print(data)
8. Using Sessions with Requests
To use a session object for making multiple requests to the same host, which can improve performance:
import requests
with requests.Session() as session:
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
response = session.get('https://api.example.com/data')
print(response.json())
To stream a large response to process it in chunks, rather than loading it all into memory:
import requests
response = requests.get('https://api.example.com/large-data', stream=True)
for chunk in response.iter_content(chunk_size=1024):
process(chunk) # Replace 'process' with your actual processing function
with open('example.txt', 'r') as file:
content = file.read()
print(content)
2. Writing to a File
To write text to a file, overwriting existing content:
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
3. Appending to a File
To add text to the end of an existing file:
with open('example.txt', 'a') as file:
file.write('\nAppend this line.')
4. Reading Lines into a List
To read a file line by line into a list:
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)
5. Iterating Over Each Line in a File
To process each line in a file:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
6. Checking If a File Exists
To check if a file exists before performing file operations:
import os
if os.path.exists('example.txt'):
print('File exists.')
else:
print('File does not exist.')
7. Writing Lists to a File
To write each element of a list to a new line in a file:
lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
for line in lines:
file.write(f'{line}\n')
8. Using With Blocks for Multiple Files
To work with multiple files simultaneously usingwithblocks:
with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
content = source.read()
destination.write(content)
9. Deleting a File
To safely delete a file if it exists:
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted.')
else:
print('File does not exist.')
10. Reading and Writing Binary Files
To read from and write to a file in binary mode (useful for images, videos, etc.):
# Reading a binary file
with open('image.jpg', 'rb') as file:
content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
file.write(content)