python - Python - read a text file with multiple lines into a list
问题描述
I would like to turn this (in a .txt file):
7316717653
1330624919
into this (in a Python list):
a_list = [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
how do I do this? I've been looking everywhere, but nothing came close to what I intended to do
解决方案
lst = []
with open('New Text Document.txt', 'r') as f: #open the file
lines = f.readlines() # combine lines of file in a list
for item in lines: # iterate through items of lines
# iterate through items in each line and remove extra space after last item in the line using strip method
for digit in item.strip():
lst.append(int(digit)) # append digits in to the list and convert them to int
print(lst)
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
推荐阅读
- google-sheets - 根据 Google 表格列过滤的数据洞察日期范围
- windows - 像ntlite一样从Windows 10中删除组件
- cakephp - 扫描ctp文件时清空PO文件
- android - 自定义键盘:ASCII 代码与 KEYCODE
- algorithm - 在大量文件中搜索固定字符串的静态列表
- excel - 如果活动单元格在表格列中,则仅复制单元格值
- python - Python 日志错误“非类型”
- amazon-web-services - KAFKA 消费者设置在本地代理后面。生产者在 AWS
- javascript - 使用来自 javascript 的 get 方法访问 php 时未定义值
- c# - 有没有办法将 RichTextBox 添加到适用于 Android 的 C# Xamarin 项目?