在保存URL到文件时,可能会遇到以下几个逻辑问题:
以下是一个示例代码,演示如何解决上述逻辑问题:
import os
import re
def save_url_to_file(url, file_path):
# Check if file exists
if not os.path.exists(file_path):
print("File path does not exist.")
return
# Check if file has read/write permissions
if not os.access(file_path, os.R_OK | os.W_OK):
print("File does not have read/write permissions.")
return
# Check if URL is valid
url_pattern = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ipv4
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
if not re.match(url_pattern, url):
print("Invalid URL.")
return
# Check if URL already exists in file
with open(file_path, 'r') as file:
if url in file.read():
print("URL already exists in file.")
return
# Save URL to file
with open(file_path, 'a') as file:
file.write(url + '\n')
print("URL saved successfully.")
在上述示例代码中,我们首先检查文件路径是否存在,并且是否有读写权限。然后,我们使用正则表达式验证URL的有效性。接下来,我们读取文件内容,检查URL是否已经存在于文件中。最后,如果通过了所有检查,我们将URL追加写入文件中。
上一篇:保存Unity GUI字段
下一篇:保存VSCode设置