用Python写一段代码从MySQL里获取一批手机号,并和我的表格里的手机号做比较,重复的不要,不重复的保存到一个新的表格里
时间: 2023-04-08 18:05:11 浏览: 184
好的,这个问题可以回答。以下是Python代码示例:
```python
import mysql.connector
# 连接MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 获取MySQL中的手机号
mycursor = mydb.cursor()
mycursor.execute("SELECT phone_number FROM phone_table")
myresult = mycursor.fetchall()
# 与表格中的手机号比较,去重
existing_numbers = set()
with open('my_table.csv', 'r') as f:
for line in f:
number = line.strip().split(',')[0]
existing_numbers.add(number)
new_numbers = []
for number in myresult:
if number[0] not in existing_numbers:
new_numbers.append(number[0])
# 将不重复的手机号保存到新的表格中
with open('new_numbers.csv', 'w') as f:
for number in new_numbers:
f.write(number + '\n')
```
希望这个代码示例能够帮到你!
阅读全文