如何在通过Python读取文本文件时保持文本文件的格式? [英] How do I maintain the format of a text file when reading a text file through Python?

查看:287
本文介绍了如何在通过Python读取文本文件时保持文本文件的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  BLAH 
我有一个.txt文件,它有一个如下所示的项目列表: ONE
TWO


$ b

我目前使用Python读取.txt文件并打印出文本行。我遇到的问题是,打印的行显示换行符 \\\
和一个逗号。看起来是这样的,当我从.txt文件打印数据时:

  BLAH \\\
,ONE \\\
,TWO \\\
,THREE \\\
,FOUR

我试过使用 .replace(\ n,,)试图至少摆脱不需要的字符,但似乎并没有工作。如何通过Python命令从.txt文件保持相同的格式?



请求,这是我的代码:

  file = open(plstemp.txt,r)
abc = str(file.readlines())
wow = abc。 replace([,).replace(],).replace(',)
print(哇)
file.close()

我所需的输出如下:

  BLAH 
ONE
TWO
THREE
FOUR


<正如怀疑,你正在使用 readlines 这将给你一个列表。列表中的每个项目是来自文件的一行。你不需要做全部替换'['。你需要认识到你实际上有一个列表。所以,做 file.readlines(),你将得到:


$ b

  ['BLAH \ n','ONE \\\
','TWO'\
','THREE\\\
','FOUR\\\
' ]

如果使用 file.read()打印出来的结果:

  BLAH 
ONE
TWO
THREE
FOUR

请记住,您仍然有'\ n',因为您因为'\ n'实际上是一个特殊字符,意思是换行符。

所以,重写你的代码,你可以简单的做(你不需要指定r,因为它默认为r):

 < code file = open(plstemp.txt)
abc = file.read()
file.close()
print(abc)


I have a .txt file where it has a list of items that look like so:

BLAH
ONE
TWO
THREE
FOUR

I'm currently using Python to read that .txt file and print out the lines of text. The issue I'm running into is that the printed lines display the newline character of \n and a comma together. It looks like so when I print the data from the .txt file:

BLAH \n, ONE \n, TWO \n, THREE \n, FOUR

I've tried using a .replace("\n,", "") in an attempt to at least get rid of the unwanted characters, but that does not seem to be working. How can I get maintain the same format from the .txt file through Python commands?

By request, here is my code:

file = open("plstemp.txt", "r")
      abc=str(file.readlines())
      wow = abc.replace("[", "").replace("]", "").replace("'", "")
      print(wow)
      file.close()

My desired output is as follows:

BLAH
ONE
TWO
THREE
FOUR

解决方案

As suspected, you are using readlines which will give you a list. Where each item in the list is a line from your file. You do not need to do that whole replacement of '['. You need to realize here you actually have a list.

So, doing file.readlines(), you will have:

['BLAH\n', 'ONE\n', 'TWO\n', 'THREE\n', 'FOUR\n']

If you use file.read() instead and print out the result of that:

BLAH
ONE
TWO
THREE
FOUR

Keep in mind, you still have a '\n', because you actually need it to have the output above, since '\n' actually is a special character meaning "newline".

So, to re-write your code, you can simply do (you don't need to specify "r" since it is "r" by default):

file = open("plstemp.txt")
abc=file.read()
file.close()
print(abc)

这篇关于如何在通过Python读取文本文件时保持文本文件的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆