[英]Python - How to add a space string (' ') to the end of every line in a text/conf file
I have a config file that i would like to add a space (' ') to the end of every line in the file 我有一个配置文件,我想在文件中每一行的末尾添加一个空格('')
File example: 文件示例:
#xxx configuration
IPaddr = 1.1.1.1<add a space here>
host = a.b.c.d<add a space here>
usrname = aaa<add a space here>
dbSID = xxx<add a space here>
i already have the number of lines in the file (using len) so i know how much time to repeat the loop of adding the space string. 我已经有文件中的行数(使用len),所以我知道多少时间重复添加空格字符串的循环。 i also know how to open a file for reading and writing.
我也知道如何打开文件进行读写。
Thank you all. 谢谢你们。
You can use fileinput with inplace=True
to update the original file: 您可以将fileinput与inplace
inplace=True
一起使用来更新原始文件:
import fileinput
import sys
for line in fileinput.input("in.txt",inplace=True):
sys.stdout.write("{} \n".format(line.rstrip()))
Or use a tempfile.NamedTemporaryFile with shutil.move : 或者将tempfile.NamedTemporaryFile与shutil.move一起使用 :
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
for line in f:
temp.write("{} \n".format(line.rstrip()))
move(temp.name,"in.txt")
You don't need to know the length of your file. 您不需要知道文件的长度。 In python files are iterators that yield lines.
在python文件中是产生线条的迭代器。 No need for c-style for-loops.
不需要c样式的for循环。
So something like this should work for you (python3 or from __future__ import print_function
): 所以这样的事情应该为您工作(python3或
from __future__ import print_function
):
with open('file.in') as infile, open('file.out', 'w') as outfile:
for line in infile:
print(line.strip() + ' ', file=outfile)
You can do this (on the same file) by opening the file for reading with "r" flag, 您可以通过打开文件以使用“ r”标志进行读取来对同一文件执行此操作,
Then, for each row in the file, add a space before the new line character ("\\n"), 然后,对于文件中的每一行,在换行符(“ \\ n”)之前添加一个空格,
And finally, open the file for writing with "w' flag, and write the updated content with writelines() function. 最后,使用“ w”标志打开要写入的文件,并使用writelines()函数写入更新后的内容。
with open('config.txt', 'r') as source:
lines = [line.replace("\n"," \n") for line in source.readlines()]
with open("config.txt", "w") as target:
target.writelines(lines)
Please note, I assume that the file is a UNIX file so it does not contain "\\r" character before the "\\n", if it is not the case, line number 2 should be: 请注意,我假设该文件是UNIX文件,因此在“ \\ n”之前不包含“ \\ r”字符,如果不是这种情况,则第2行应为:
lines = [line.replace("\r\n"," \r\n") for line in source.readlines()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.