读取文件python时删除字符

时间:2013-01-04 06:25:12

标签: python latex readfile

我有一个LaTeX文件,我想在表单字段中显示。 输入文件:

...
\begin{center}
    \vspace{-5mm}
    \noindent
    \textbf{\large Thank You! for Using}
\end{center}
...

我使用readlines()

在python中阅读
'\\begin{center}' '\n'

......等等。

我想要转义字符<没有' \ n' ' \'' ' \吨'等>要删除,以便可以将读取的内容放入表单字段。怎么办呢?

2 个答案:

答案 0 :(得分:0)

您可以使用适用于Python字符串的replace函数。

$> a = 'xyz\nbcd'
$> b = a.replace('\n','') # b would be 'xyzbcd'

答案 1 :(得分:0)

我不太确定你是否真的要删除每一行末尾只有尾随\n的所有转义字符。这是许多python程序员在第一次阅读文件时遇到的常见问题,我不久前就已经拥有了。

readlines()会保留尾随\n,以便简单的"".join(lines)可以恢复原始文件内容。

只需从每一行中删除尾随\n

# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip()
    print line
    lines2.append(line)
fh.close()

输出

# -*- coding: utf-8 -*-

"""

Sample for readlines and trailing newline characters

"""

import sys



lines1 = []

fh = open(sys.argv[0],"r")

for line in fh.readlines():

    print line

    lines1.append(line)

fh.close()



lines2 = []

fh = open(sys.argv[0],"r")

for line in fh:

    line = line.rstrip("\n")

    print line

    lines2.append(line)

fh.close()


# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip("\n")
    print line
    lines2.append(line)
fh.close()

您也可以编写line.rstrip("\n")来明确地仅删除换行符而不是所有空白字符。