【问题标题】:Reading lines from text file in python (windows)从python中的文本文件中读取行(windows)
【发布时间】:2011-09-07 23:09:09
【问题描述】:

我正在研究一个简单的导入例程,它将文本文件转换为我们系统的 json 文件格式。

导入json # 打开文本文件进行阅读 txtFile = open('Boating.Make.txt', 'r') # 创建选择列表 obj picklistObj = dict() picklistObj['name'] = 'Boating.Make' picklistObj['items'] = list() 我 = 0 # 遍历文本文件中的每个make 对于 txtFile 中的行: picklistItemObj = dict() picklistItemObj['value'] = str(i) picklistItemObj['text'] = line.strip() picklistItemObj['selectable'] = True picklistObj['items'].append(picklistItemObj) 我 = 我 + 1 txtFile.close() picklistJson = json.dumps(picklistObj, indent=4) 打印选择列表Json picklistFile = open('Boating.Make.json', 'w') picklistFile.write(picklistJson) 选择列表文件.close()

我的问题是,为什么我需要“条”?我认为 python 应该神奇地知道我当前所处的任何环境的换行符常量。我错过了什么吗?

我应该澄清一下,我正在读取的文本文件是一个 ASCII 文件,其中包含以“\r\n”分隔的文本行。

【问题讨论】:

    标签: python windows json io


    【解决方案1】:

    Python 在枚举行时保留换行符。例如,当枚举一个文本文件时,如

    foo
    bar
    

    你会得到两个字符串:"foo\n""bar\n"。如果您不想要终端换行符,请致电strip()

    顺便说一句,我不喜欢这种行为。

    【讨论】:

    • 看来你是对的。如果我使用'U'显式地将文件作为文本打开并不重要,行为是相同的。这似乎与“通用换行符”的心态不符。
    【解决方案2】:

    this

    Python 通常是用通用构建的 换行支持;供应“U”打开 文件作为文本文件,但行可能 被以下任何一种终止: Unix 行尾约定 '\n', Macintosh 约定 '\r',或 Windows 约定“\r\n”

    【讨论】:

    • 在读取文件时,显然将“U”附加到文件打开模式不会传递到迭代器(for 语句)。将我的文件打开模式修改为“rU”并没有什么不同。
    【解决方案3】:

    您需要 strip() 因为“for line in file:”将行终止符保留在行上。文档中没有明确说明(至少在我正在查看的 2.71 文档中)。但它的功能类似于 file.readline(),后者明确声明它保留换行符。

    【讨论】:

      【解决方案4】:

      在 Python 解释器中尝试以下操作,看看该语言的作用:

      open('test1.txt', 'wb').write(b'Hello\nWorld!')
      open('test2.txt', 'wb').write(b'Hello\r\nWorld!')
      print(list(open('test1.txt'))) # Shows ['Hello\n', 'World!']
      print(list(open('test2.txt'))) # Shows ['Hello\n', 'World!']
      

      Python 确实可以识别正确的换行符。您可能不想在字符串上使用strip,而是改为编写myString.replace('\n', '')。检查文档:

      >>> help(str.strip)
      Help on method_descriptor:
      
      strip(...)
          S.strip([chars]) -> str
      
          Return a copy of the string S with leading and trailing
          whitespace removed.
          If chars is given and not None, remove characters in chars instead.
      
      >>> help(str.replace)
      Help on method_descriptor:
      
      replace(...)
          S.replace(old, new[, count]) -> str
      
          Return a copy of S with all occurrences of substring
          old replaced by new.  If the optional argument count is
          given, only the first count occurrences are replaced.
      

      【讨论】:

      • 如上所述,调用 strip 和 replace 之间实际上没有区别。
      • 如果行的开头和结尾有空格需要保留,strip 不足以保证数据完整性。如果您正在阅读行,那么如果保留前导和尾随空格对您很重要,您可能至少需要致电 myString.strip('\n')
      猜你喜欢
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多