【问题标题】:Load a text file with values into a tuple in Python将带有值的文本文件加载到 Python 中的元组中
【发布时间】: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


    【解决方案1】:
    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')
    

    【讨论】:

    • 选择这个作为接受的答案是因为另一个没有 for 循环的更简单的答案最终会在元组末尾创建一个空字符串项。
    【解决方案2】:
    with open('file.txt','r') as f:
         tup = tuple(f.read().split('\n'))
    
    tup
    ('word1', 'word2', 'word3', 'word4', 'word5')
    

    【讨论】:

      【解决方案3】:

      您可以创建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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多