改进代码import requests with open('PRRSV.txt','r') as f: file_names = f.readlines() for file_name in file_names: file_name = file_name.strip() url = f"ftp://ftp.ncbi.nlm.nih.gov/genomes/genbank/all/{file_name}/{file_name}_genomic.gbff.gz" response = requests.get(url) with open(f'{file_name}.gbff.gz', 'wb') as f: f.write(response.content)
时间: 2024-04-27 10:21:51 浏览: 125
Python库 | http_seekable_file-0.4.0-py3-none-any.whl
你的代码似乎是从NCBI下载一些基因组数据文件,然后保存到本地。如果你想改进代码,可以考虑以下几点:
1. 引入异常处理机制,以应对可能出现的网络连接异常、文件读写异常等情况。
2. 使用多线程或异步IO等技术,以提高下载的效率。
3. 将文件的下载和保存分开,以便于维护和修改。
4. 添加一些日志记录,以便于排查问题和追踪程序的执行情况。
下面是一个可能的改进版本的代码示例,供你参考:
```python
import os
import logging
import requests
import concurrent.futures
# 设置日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)
logger.addHandler(sh)
# 设置下载目录和线程数
DOWNLOAD_DIR = 'genomes'
THREADS = 4
# 下载文件的函数
def download_file(url, file_path):
try:
logger.debug(f"downloading {url}")
response = requests.get(url, stream=True)
response.raise_for_status()
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
logger.debug(f"downloaded {file_path}")
except Exception as e:
logger.error(f"failed to download {url}: {e}")
# 下载文件列表中的所有文件
def download_files(file_list):
with concurrent.futures.ThreadPoolExecutor(max_workers=THREADS) as executor:
futures = []
for file_name in file_list:
file_name = file_name.strip()
url = f"ftp://ftp.ncbi.nlm.nih.gov/genomes/genbank/all/{file_name}/{file_name}_genomic.gbff.gz"
file_path = os.path.join(DOWNLOAD_DIR, f"{file_name}.gbff.gz")
os.makedirs(os.path.dirname(file_path), exist_ok=True)
futures.append(executor.submit(download_file, url, file_path))
for future in concurrent.futures.as_completed(futures):
future.result()
# 主函数
def main():
with open('PRRSV.txt', 'r') as f:
file_names = f.readlines()
download_files(file_names)
if __name__ == '__main__':
main()
```
阅读全文