Python - 将包含多行的文本文件读入列表
Python - read a text file with multiple lines into a list
我想打开这个(在 .txt 文件中):
7316717653
1330624919
进入此(在 Python 列表中):
a_list = [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
我该怎么做?我一直在到处寻找,但没有什么能接近我打算做的事情
with open('txtfile', 'r') as f:
x = f.read()
print [y for y in list(x) if y != '\n']
这是一个完整的解决方案:
num = '''7316717653
1330624919'''
num = num.replace('\n', '')
# Write to a text file:
with open('filename.txt', 'w') as f:
f.write(num)
# Now write to a Python List:
fd = open('filename.txt','rU')
chars = []
for line in fd:
chars.extend(line)
Output is: [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
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]
我想打开这个(在 .txt 文件中):
7316717653
1330624919
进入此(在 Python 列表中):
a_list = [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
我该怎么做?我一直在到处寻找,但没有什么能接近我打算做的事情
with open('txtfile', 'r') as f:
x = f.read()
print [y for y in list(x) if y != '\n']
这是一个完整的解决方案:
num = '''7316717653
1330624919'''
num = num.replace('\n', '')
# Write to a text file:
with open('filename.txt', 'w') as f:
f.write(num)
# Now write to a Python List:
fd = open('filename.txt','rU')
chars = []
for line in fd:
chars.extend(line)
Output is: [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]
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]