python:文件i / o计数字符没有新行

时间:2014-03-29 22:52:02

标签: python python-3.x

我有一个名为number.txt的文本文件。它包含以下内容:

0
1
2
3

我的代码:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read() 
   inFile.close()
   print(len(text))
main()

我尝试使用上面的代码打印出文件中有多少个字符。它打印出8,但只有4个字符。 我知道当python读入文件时,它会在每行之后添加换行符,这可能是额外的字符。我怎么摆脱这个?

6 个答案:

答案 0 :(得分:3)

该文件在每行之间包含换行符。要对其进行过滤,您可以重新创建不带replacesplit或类似新行的字符串,或者计算新行并从长度中减去它们(这样更快/更有效)。 / p>

with open("number.txt", "r") as file:
    text = file.read()
length_without_newlines = len(text) - text.count('\n')

编辑:正如@lvc所说,Python将所有行结尾转换为' \ n' (0x0A),包括windows换行符(' \ r \ n'或[0x0D,0x0A]),因此只需要搜索' \ n'在寻找新的行字符时。

答案 1 :(得分:0)

正如安东尼奥在评论中所说,新行字符在文件中。 如果你愿意,你可以删除它们:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read() 
   inFile.close()
   text = text.replace('\n', '')  # Replace new lines with nothing (empty string).
   print(len(text))
main()

答案 2 :(得分:0)

你的剧本答案是正确的:事实上新行也是人物(他们只是看不见!)

要省略换行符(在\n\r\n的字符串中引用),则必须用空字符串替换它们。

请参阅此代码:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read()
   text = text.replace("\r\n","") #in windows, new lines are usually these two 
   text = text.replace("\n","")   

caracters。        inFile.close()        打印(LEN(文本))     main()的

有关\r\n\n的更多信息,请尝试:http://en.wikipedia.org/wiki/Newline

答案 3 :(得分:0)

使用string.rstrip('\n')。这将删除字符串右侧的换行符,而不是其他内容。请注意,无论平台如何,python都应将所有换行符转换为\n。我还建议迭代文件的行,而不是将它全部转储到内存中,以防你有一个大文件。

示例代码:

if __name__ == '__main__':
   count = 0
   with open("number.txt", "r") as fin):
       for line in fin:
           text = line.rstrip('\n')
           count += len(text)
   print(count)

答案 4 :(得分:0)

试试这个:

if __name__ == '__main__':
    with open('number.txt', 'rb') as in_file:
        print abs(len(in_file.readlines()) - in_file.tell())

答案 5 :(得分:0)

在打印行中执行此操作:

    print(len(text.replace("\n", "")))