![](/img/trans.png)
[英]Remove whitespaces from beginning and end of each line in a file in python
[英]Python- need to append characters to the beginning and end of each line in text file
我应该以我是一个完整的Python新手为序。
我试图创建一个脚本,该脚本将遍历目录及其子目录以查找文本文件。 当遇到文本文件时,它将解析该文件并将其转换为NITF XML并上传到FTP目录。
此时,我仍在努力将文本文件读入变量,以便可以在正确的位置将其插入XML文档。 文本文件的示例如下。
Headline
Subhead
By A person
Paragraph text.
这是我到目前为止的代码:
with open("path/to/textFile.txt") as f:
#content = f.readlines()
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
pth = os.getcwd()
print head,sub,auth,data,pth
我的问题是:如何遍历文本文件(数据)的主体并将每一行包装在HTML P标签中? 例如;
<P>line of text in file </P> <P>Next line in text file</p>
。
就像是
output_format = '<p>{}</p>\n'.format
with open('input') as fin, open('output', 'w') as fout:
fout.writelines( output_format(line.strip()) for line in fin )
with open('infile') as fin, open('outfile',w) as fout:
for line in fin:
fout.write('<P>{0}</P>\n'.format(line[:-1]) #slice off the newline. Same as `line.rstrip('\n')`.
#Only do this once you're sure the script works :)
shutil.move('outfile','infile') #Need to replace the input file with the output file
假设您想将新内容写回到原始文件中:
with open('path/to/textFile.txt') as f:
content = f.readlines()
with open('path/to/textFile.txt', 'w') as f:
for line in content:
f.write('<p>' + line.strip() + '</p>\n')
在这种情况下,您可能应该更换
data=f.read()
有:
data = '\n'.join("<p>%s</p>" % l.strip() for l in f)
在这里使用data=f.readlines()
,
然后遍历数据并尝试如下操作:
for line in data:
line="<p>"+line.strip()+"</p>"
#write line+'\n' to a file or do something else
附加
和<\\ p>每行
例如:
data_new=[]
data=f.readlines()
for lines in data:
data_new.append("<p>%s</p>\n" % data.strip().strip("\n"))
您可以使用fileinput
模块fileinput
修改一个或多个文件,并根据需要创建可选的备份文件(有关详细信息,请参见其文档 )。 这是用来处理一个文件的。
import fileinput
for line in fileinput.input('testinput.txt', inplace=1):
print '<P>'+line[:-1]+'<\P>'
'testinput.txt'
参数也可以是两个或多个文件名的序列,而不是一个文件名,这在您使用os.walk()
生成目录中的文件列表时特别有用。它的子目录进行处理(您可能应该这样做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.