![](/img/trans.png)
[英]How can I read multiple text files and save them individually as a Pandas Dataframe?
[英]how can I write multiple files with text changing in each of them
我有一個格式的斑點文件(可以像txt一樣進行編輯)
datavar 0 pictype datavar 1 absmag texturevar pictype #The texture filename to associate with txnum 1 texture -a 24 24_rot_0001.sgi #xyz no. lum 100.0 100.0 100.0 24 10.0
我需要做的是創建“ n”個文件,每個文件名為rot_“ n” .speck,文件中唯一的更改是將rot_0001.sgi更改為rot_00“ n” .sgi。 我知道大概很簡單的python循環可以執行此操作。 但我不知道它將采取的形式。 你能幫我嗎?
沒錯,您可以使用FOR循環來完成此操作。 我使用以下代碼編寫了4個名為rot_n.spek
文件。 我使用了上面顯示的文件來創建文件。
import re
for j in range(4):
file_name = "rot_{:04d}.spek".format(j)
with open(file_name, 'w+') as new_file:
with open('simple.txt', 'r') as old_file:
for line in old_file:
new_file.write(re.sub(r"24_rot_\d+.sgi",
"24_rot_00{:04d}.sgi".format(j), line ) )
如果因為每次總是閱讀同一文件,也可以使用字符串替換 。
new_file.write(line.replace("24_rot_0001.sgi", "24_rot_{:04d}.sgi".format(j)))
我發現這個答案很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.