![](/img/trans.png)
[英]How to change the first charcater of every new line in a file using python
[英]How to insert a new line before the first line in a file using python?
更多詳情如下:
1st line
2nd line
3rd line
4th line
...
現在想在1st line
之前插入一個名為zero line
的新1st line
。 文件如下所示:
zero line
1st line
2nd line
3rd line
4th line
...
我知道sed
命令可以完成這項工作,但是如何使用 python 來完成呢? 謝謝
你可以使用文件fileinput
>>> import fileinput
>>> for linenum,line in enumerate( fileinput.FileInput("file",inplace=1) ):
... if linenum==0 :
... print "new line"
... print line.rstrip()
... else:
... print line.rstrip()
...
這可能很有趣
http://net4geeks.com/index.php?option=com_content&task=view&id=53&Itemid=11
適應你的問題:
# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("zero line\n\n")
# write the original contents
f.write(text)
f.close()
打開文件並將內容讀入“文本”。
關閉文件
使用參數“w”重新打開文件進行寫入
寫入文本以添加到文件中
將文件的原始內容寫入文件
關閉文件
閱讀鏈接中的警告。
編輯:
但請注意,這並不完全安全,如果您的 Python 會話在第二次打開文件后和再次關閉文件之前崩潰,您將丟失數據。
這是一個實現,它修復了迄今為止提出的其他方法中的一些缺陷:
fileinput
版本不支持fileinput
尾隨空格——文件fileinput
版本會 它模仿fileinput
的錯誤處理:
import os
def prepend(filename, data, bufsize=1<<15):
# backup the file
backupname = filename + os.extsep+'bak'
try: os.unlink(backupname) # remove previous backup if it exists
except OSError: pass
os.rename(filename, backupname)
# open input/output files, note: outputfile's permissions lost
with open(backupname) as inputfile, open(filename, 'w') as outputfile:
# prepend
outputfile.write(data)
# copy the rest
buf = inputfile.read(bufsize)
while buf:
outputfile.write(buf)
buf = inputfile.read(bufsize)
# remove backup on success
try: os.unlink(backupname)
except OSError: pass
prepend('file', '0 line\n')
如果可以復制文件,您可以使用cat
實用程序。 它可能更有效:
import os
from subprocess import PIPE, Popen
def prepend_cat(filename, data, bufsize=1<<15):
# backup the file
backupname = filename + os.extsep+'bak'
try: os.unlink(backupname)
except OSError: pass
os.rename(filename, backupname)
# $ echo $data | cat - $backupname > $filename
with open(filename, 'w') as outputfile: #note: outputfile's permissions lost
p = Popen(['cat', '-', backupname], stdin=PIPE, stdout=outputfile)
p.communicate(data)
# remove backup on success
if p.poll() == 0:
try: os.unlink(backupname)
except OSError: pass
prepend_cat('file', '0 line\n')
with open(filename, 'r+') as f:
lines = f.readlines()
lines.insert(0, 'zero line\n')
f.seek(0)
f.writelines(lines)
代碼
L = list()
f = open('text2.txt', 'r')
for line in f.readlines():
L.append(line)
L.insert(0,"Zero\n")
f.close()
fi = open('text2.txt', 'w')
for line in xrange(len(L)):
fi.write(L[line])
fi.close()
文本2.txt
Hello
The second line
3
4
5
6
輸出
Zero
Hello
The second line
3
4
5
6
但是,對於大文件,這可能會占用大量內存且耗時。
如果您擔心第 31 行之類的問題,我會在 num 上做一個 mod%10,以獲得更准確的版本。
如果這有幫助,或者您想要更好的版本,請告訴我。 此外,如果您想要更好的格式,請查看 ljust 和 rjust 的左對齊和右對齊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.