【问题标题】:Python difference between reading int file and str filePython读取int文件和str文件的区别
【发布时间】:2016-02-16 19:29:49
【问题描述】:

打开和返回仅包含字符串的文件与打开和返回包含 int 的文件有什么区别。对于我阅读 str 的代码是

    with open(file_name, 'r') as f:
        return f.read().splitlines()

只是想知道读取字符串和读取 [1 2 3 4 5 6 7] 之类的 int 列表并返回 [1,2,3,4,5,6,7] 之间有什么区别

【问题讨论】:

  • 请详细说明您的问题

标签: python return


【解决方案1】:

open(file_name, 'r') 读取文件总是会给你字符串。如果您知道事实,则数据是数字的。你可以这样做:

result = []
with open(file_name, 'r') as fin:
    for line in fin:
        result.append([int(word) for word in line.split()])
    return result

如果您知道有些数据可以是整数,有些可以是字符串。然后你可以尝试转换:

result = []
with open(file_name, 'r') as fin:
    for line in fin:
        clean_line = []
        for word in line.split():
            try:
                clean_line.append(int(word))
            except: 
                clean_line.append(word)
        result.append(clean_line)
return result

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2018-06-12
    • 2012-04-24
    相关资源
    最近更新 更多