将包含值的文本文件加载到 Python 中的元组中
Load a text file with values into a tuple in Python
我有文本文件 file.txt
,其值如下:
word1
word2
word3
word4
word5
我要的是Python3这样的元组:
my_tuple = ('word1','word2','word3','word4','word5')
有什么建议吗?
with open('file.txt','r') as f:
my_tuple=tuple(line.strip('\n') for line in f)
print(my_tuple)
# ('word1','word2','word3','word4','word5')
with open('file.txt','r') as f:
tup = tuple(f.read().split('\n'))
tup
('word1', 'word2', 'word3', 'word4', 'word5')
您可以创建一个 list
,然后将其转换为 tuple
。
import os.path
text_file = open("file.txt", encoding="utf8")
my_list = []
for line in text_file:
my_list.append(line)
my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))
我有文本文件 file.txt
,其值如下:
word1
word2
word3
word4
word5
我要的是Python3这样的元组:
my_tuple = ('word1','word2','word3','word4','word5')
有什么建议吗?
with open('file.txt','r') as f:
my_tuple=tuple(line.strip('\n') for line in f)
print(my_tuple)
# ('word1','word2','word3','word4','word5')
with open('file.txt','r') as f:
tup = tuple(f.read().split('\n'))
tup
('word1', 'word2', 'word3', 'word4', 'word5')
您可以创建一个 list
,然后将其转换为 tuple
。
import os.path
text_file = open("file.txt", encoding="utf8")
my_list = []
for line in text_file:
my_list.append(line)
my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))