Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- port
- IOS
- swift
- 날짜
- 맛집
- urllib
- flutter
- MySQL
- MS-SQL
- sqlite
- ubuntu
- tensorflow
- GIT
- ASP
- 다이어트
- pandas
- 리눅스
- PER
- Linux
- javascript
- mssql
- Unity
- python
- 라즈베리파이
- PyQt5
- PyQt
- Excel
- node.js
- 함수
- 유니티
Archives
아미(아름다운미소)
파일에 최대 5줄까지만 유지하면서 새로운 내용을 추가 본문
def write_limited_lines(file_path, new_line, max_lines=5):
# 기존 파일 읽기
try:
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
except FileNotFoundError:
lines = []
# 기존 내용에서 마지막 (max_lines - 1) 줄만 유지
lines = lines[-(max_lines - 1):]
# 새로운 줄 추가
lines.append(new_line + "\n")
# 파일 다시 쓰기
with open(file_path, "w", encoding="utf-8") as f:
f.writelines(lines)
# 예제 실행
file_path = "orders.txt"
new_order = "매수;005930;시장가;1;0;매수전"
write_limited_lines(file_path, new_order)
'랭귀지 > python' 카테고리의 다른 글
python for timeout (1) | 2024.11.15 |
---|---|
minikube ,docker 설치 (0) | 2024.11.13 |
int 아닐때 0 반환 (0) | 2024.10.23 |
FCMNotifier class (0) | 2024.09.12 |
HTTP v1 API를 사용하여 db연동 푸시 알림을 전송하는 샘플 코드 (1) | 2024.09.12 |