LoginSignup
3
0

More than 3 years have passed since last update.

[質問]Pythonでtxtファイル内の行を指定して上書きしたい

Posted at

Pythonでtxtファイル内の行を指定して上書きしたい

データベースとしてtxtファイルを使用しているのですが、ファイル内の指定した行の上書を行いたいです。

やってみたこと

指定行の上書と言うのが分からなかったため、txtファイルの中身全体をreadlinesで行別にlist化し、特定の要素を書き換えてwritelines(list)で上書きしていました。

test.txt
Hello
World
code.py
import os

path = "/data/test.txt"
line_num = 1 # 上書きする行番号(場合によっては変わる)
temp = "Python" # 上書きしたい内容

with open(path) as file:
    list = file.readlines

print(list)
#Hello
#World

list[line_num] = temp
print(list)
#Hello
#Python

with open(path, mode="w") as file:
    file.writelines(list)

この様に。
流石にもう少しいい方法があるのではと思い、質問に至った次第です。

3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0