Python 列表、元组及相关操作详解
1. 文件操作与列表
1.1 将列表写入文件
以下代码展示了如何将一个数字列表保存到文件中:
# This program saves a list of numbers to a file.
def main():
# Create a list of numbers.
numbers = [1, 2, 3, 4, 5, 6, 7]
# Write the list to the file.
with open('numberlist.txt', 'w') as outfile:
for item in numbers:
outfile.write(str(item) + '\n')
# Call the main function.
if __name__ == '__main__':
main()
操作步骤如下:
1. 创建一个包含数字的列表。
2. 以写入模式打开文件 numberlist.txt 。
3. 遍历列表,将每个元素转换为字符串并添加换行符后写入文件。
1.2 从文件读取列表
以下代码展示了如何从文件中读取数字并转换为列表:
# This program reads numbers from a file into a list.
def main(
超级会员免费看
订阅专栏 解锁全文
834

被折叠的 条评论
为什么被折叠?



