怎么编程一个批量保存联系人的脚本
时间: 2023-12-06 12:40:58 浏览: 41
这个问题的答案取决于你要保存联系人的具体位置和格式。如果你想保存到本地的文件中,可以使用Python的csv模块或者pandas库来创建一个csv文件并写入联系人信息。以下是一个csv模块的示例代码:
```python
import csv
# 定义联系人列表
contacts = [
{'name': '张三', 'phone': '1234567890', 'email': 'zhangsan@example.com'},
{'name': '李四', 'phone': '0987654321', 'email': 'lisi@example.com'},
{'name': '王五', 'phone': '1357924680', 'email': 'wangwu@example.com'}
]
# 打开csv文件
with open('contacts.csv', mode='w', newline='') as file:
# 创建csv写入对象
writer = csv.writer(file)
# 写入表头
writer.writerow(['Name', 'Phone', 'Email'])
# 写入联系人信息
for contact in contacts:
writer.writerow([contact['name'], contact['phone'], contact['email']])
```
如果你想保存到Google Contacts中,可以使用Google API来完成这个任务。以下是一个使用Google API的示例代码:
```python
import os
import google.oauth2.credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.auth.transport.requests import Request
# 设置授权范围和应用凭证
SCOPES = ['https://www.googleapis.com/auth/contacts']
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'My Contacts'
# 获取授权凭证
def get_credentials():
credentials = None
if os.path.exists('token.json'):
with open('token.json', 'r') as token:
credentials = google.oauth2.credentials.Credentials.from_authorized_user_info(
token.read(), SCOPES)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = google.auth.OAuth2FlowFromClientSecrets(
CLIENT_SECRET_FILE, SCOPES)
credentials = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(credentials.to_json())
return credentials
# 创建联系人
def create_contact(name, phone, email):
credentials = get_credentials()
service = build('people', 'v1', credentials=credentials)
person = {
'names': [{'givenName': name}],
'phoneNumbers': [{'value': phone}],
'emailAddresses': [{'value': email}]
}
try:
service.people().createContact(parent='people/me', body=person).execute()
print('Contact created: {}'.format(name))
except HttpError as error:
print('An error occurred: {}'.format(error))
# 定义联系人列表
contacts = [
{'name': '张三', 'phone': '1234567890', 'email': 'zhangsan@example.com'},
{'name': '李四', 'phone': '0987654321', 'email': 'lisi@example.com'},
{'name': '王五', 'phone': '1357924680', 'email': 'wangwu@example.com'}
]
# 创建联系人
for contact in contacts:
create_contact(contact['name'], contact['phone'], contact['email'])
```
请注意,在使用Google API之前,你需要先创建一个Google Cloud Platform项目并启用People API,并获取相应的应用凭证和授权范围。