~~NOCACHE~~
## 2.基本編-ファイル読み書き(Python)
### JSON
#### 読み込み
--> JSONサンプル(C:¥test.json)#
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "ap-northeast-1",
"eventTime": "2023-01-01T03:18:10.125Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:AIDASKYV2RVOKDAPXYZKE"
},
"requestParameters": {
"sourceIPAddress": "192.168.0.1"
},
"responseElements": {
"x-amz-request-id": "WS9W6BQTAWAKYS83",
"x-amz-id-2": "eSbYcHtAe0AIdyGG2swmnQBJ590g/jid4n4qw/AnTd7Ww5srME1O9pIvEJrGXxaS2AhXBxEXsjlL5cA3xG4KTBkSoih0Zv9A"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "aac92357-06c7-49ab-8aa3-86e163aa4e12",
"bucket": {
"name": "s3-bucket",
"ownerIdentity": {
"principalId": "A10X0TF2OAHF1S"
},
"arn": "arn:aws:s3:::mnz-aws-logs"
},
"object": {
"key": "Upload.file",
"size": 5593,
"eTag": "a8be190679cc809d0a465117960d5acf",
"sequencer": "0063B0FB72159B3868"
}
}
}
]
}
<--
import json
#### with open
with open('C:\\test.json', 'r') as json_file:
json_object = json.load(json_file)
print(json_object)
#### open
json_file = open('C:\\test.json', 'r')
json_object = json.load(json_file)
print (json_object)
json_file.close()
#### 書き込み
import json
json_data = {
"s3": [
{
"s3SchemaVersion": "1.0",
"configurationId": "aac92357-06c7-49ab-8aa3-86e163aa4e12",
"bucket": {
"name": "s3-bucket",
"ownerIdentity": {
"principalId": "A10X0TF2OAHF1S"
}
}
}
]
}
#### with open
with open('C:\\test.json', 'w') as text_file:
json.dump(json_data, text_file, ensure_ascii=False, indent=2)
#### open
json_file = open('C:\\test.json', 'w')
json.dump(json_data, json_file, ensure_ascii=False, indent=2)
json_file.close()
### TEXT
#### 読み込み
#### with open
with open('C:\\test.txt', 'r') as text_file:
text_object = text_file.read()
print(text_object)
#### open
text_file = open('C:\\test.txt', 'r')
text_object = text_file.read()
print(text_object)
text_file.close()
#### 書き込み
text_data = """\
line1
line2
line3\
"""
#### with open
with open('C:\\test.txt', 'w') as text_file:
text_file.write(text_data)
#### open
text_file = open('C:\\test.txt', 'w')
text_file.write(text_data)
text_file.close()
{{tag>Python}}