本文介绍了从Python中的文本文件读取行(Windows)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个简单的导入例程,该例程将使用python将文本文件转换为json文件格式.

I am working on a simple import routine that translates a text file to a json file format for our system in python.


import json

# Open text file for reading
txtFile = open('Boating.Make.txt', 'r')

# Create picklist obj
picklistObj = dict()
picklistObj['name'] = 'Boating.Make'
picklistObj['items'] = list()

i = 0
# Iterate through each make in text file
for line in txtFile:
    picklistItemObj = dict()
    picklistItemObj['value'] = str(i)
    picklistItemObj['text'] = line.strip()
    picklistItemObj['selectable'] = True
    picklistObj['items'].append(picklistItemObj)
    i = i + 1
txtFile.close()

picklistJson = json.dumps(picklistObj, indent=4)
print picklistJson

picklistFile = open('Boating.Make.json', 'w')
picklistFile.write(picklistJson)
picklistFile.close()

我的问题是,为什么我需要条带"?我以为python在我目前所处的任何环境下都应该神奇地知道换行常量.我是否缺少某些内容?

My question is, why do I need the "strip"? I thought that python was supposed to magically know the newline constant for whatever environment I am currently in. Am I missing something?

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

I should clarify that the text file I am reading from is an ASCII file that contains lines of text separated '\r\n'.

推荐答案

Python在枚举行时保留换行符.例如,在枚举诸如

Python keeps the new line characters while enumerating lines. For example, when enumerating a text file such as

foo
bar

您将获得两个字符串:"foo\n""bar\n".如果您不希望终端换行符,请致电strip().

you get two strings: "foo\n" and "bar\n". If you don't want the terminal new line characters, you call strip().

顺便说一下,我不是这种行为的粉丝.

I am not a fan of this behavior by the way.

这篇关于从Python中的文本文件读取行(Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:46