在Jupyter Notebook中如何用Python从文本文件导入坐标到citylist列表
从cities8文件读取坐标到citylist的实现方法
先看你的文件内容(如下方图片所示),每行包含一组x、y坐标,可用以下两种方式实现需求:

方法一:基础文件读取方式
适合空格/制表符分隔的坐标格式,代码简洁直接:
citylist = [] # with语句会自动处理文件关闭,避免资源泄漏 with open('cities8.txt', 'r') as file: for line in file: # 去除行首尾空白字符,分割成坐标字符串 coords = line.strip().split() # 跳过空行(如果文件里存在的话) if not coords: continue # 转换为数值类型,需要整数的话把float改成int x, y = float(coords[0]), float(coords[1]) # 把坐标以元组形式添加到列表 citylist.append((x, y))
方法二:使用csv模块(规范处理分隔文件)
如果坐标用逗号或其他固定分隔符分隔,用csv模块更稳妥:
import csv citylist = [] with open('cities8.txt', 'r') as file: # 指定分隔符,你的文件是空格分隔就用' ',逗号分隔用',' reader = csv.reader(file, delimiter=' ') # 如果文件有表头,先执行next(reader)跳过第一行 for row in reader: if not row: continue x, y = float(row[0]), float(row[1]) citylist.append((x, y))
执行完代码后,citylist就会存储所有读取到的坐标对。
内容的提问来源于stack exchange,提问作者Xmachina
相关产品推荐
相关产品推荐

