JSON 파일을 읽고 변수를 사용하여 특정 폴더와 파일을 선택하고 다른 곳에 저장하는 스크립트를 만들려고합니다.
내 JSON은 다음과 같습니다.
{
"source_type": "folder",
"tar_type": "gzip",
"tar_max_age": "10",
"source_include": {"/opt/myapp/config", "/opt/myapp/db, /opt/myapp/randomdata"}
"target_type": "tar.gzip",
"target_path": "/home/user/targetA"
}
지금까지이 Python 코드가 있습니다.
import time
import os
import tarfile
import json
source_config = '/opt/myapp/config.JSON'
target_dir = '/home/user/targetA'
def main():
with open('source_config', "r").decode('utf-8') as f:
data = json.loads('source_config')
for f in data["source_include", str]:
full_dir = os.path.join(source, f)
tar = tarfile.open(os.path.join(backup_dir, f+ '.tar.gzip'), 'w:gz')
tar.add(full_dir)
tar.close()
for oldfile in os.listdir(backup_dir):
if str(oldfile.time) < 20:
print("int(oldfile.time)")
내 역 추적은 다음과 같습니다.
Traceback (most recent call last):
File "/Users/user/Documents/myapp/test/point/test/Test2.py", line 16, in <module>
with open('/opt/myapp/config.json', "r").decode('utf-8') as f:
AttributeError: 'file' object has no attribute 'decode'
이 문제를 어떻게 해결합니까?
.decode()
파일 개체에서 직접 호출하려고 합니다. 일반적으로 읽기 행에서 대신 수행합니다. 그러나 JSON의 경우이 작업을 수행 할 필요가 없습니다 . json
라이브러리는 당신을 위해 이것을 처리합니다.
json.load()
(no s
)를 사용 하여 파일 객체에서 직접로드합니다.
with open(source_config) as f:
data = json.load(f)
다음으로 다음을 사용하여 source_include
키 주소를 지정해야합니다 .
for entry in data["source_include"]:
base_filename = os.path.basename(entry)
tar = tarfile.open(os.path.join(backup_dir, base_filename + '.tar.gzip'), 'w:gz')
tar.add(full_dir)
tar.close()
source_include가 사전이 아닌 배열이되도록 JSON도 수정해야합니다.
{
"source_type": "folder",
"tar_type": "gzip",
"tar_max_age": "10",
"source_include": ["/opt/myapp/config", "/opt/myapp/db", "/opt/myapp/randomdata"],
"target_type": "tar.gzip",
"target_path": "/home/user/targetA"
}
다음 os.listdir()
으로 문자열 (경로가없는 상대 파일 이름) 인을 사용하여 파일 이름을 반복 합니다. 문자열에는 .time
속성 이 없습니다. 파일 타임 스탬프를 읽으려면 os.stat()
대신 호출 을 사용해야 합니다.
for filename in os.listdir(backup_dir):
path = os.path.join(backup_dir, filename)
stats = os.stat(path)
if stats.st_mtime < time.time() - 20:
# file was modified less than 20 seconds ago
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다