【发布时间】:2020-06-01 01:21:21
【问题描述】:
我有文本文件file.txt,其值如下:
word1
word2
word3
word4
word5
我想要的是 Python 3 中这样的元组:
my_tuple = ('word1','word2','word3','word4','word5')
有什么建议吗?
【问题讨论】:
标签: python python-3.x file tuples file-handling
我有文本文件file.txt,其值如下:
word1
word2
word3
word4
word5
我想要的是 Python 3 中这样的元组:
my_tuple = ('word1','word2','word3','word4','word5')
有什么建议吗?
【问题讨论】:
标签: python python-3.x file tuples file-handling
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))
【讨论】: