0

If I have to deal with a file many times in a script. Basically if I need to read it at the beginning of my script, and write it at the end. Is it better to do:

f = open("myfile", "r")
lines = f.readlines()
f.close()
# ...
# Edit some lines
# ...
f = open("myfile", "w")
f.write(lines)
f.close()

Or:

f = open("myfile", "r+")
lines = f.readlines()
# ...
# Edit some lines
# ...
f.seek(0)
f.truncate()
f.write(lines)
f.close()

By "better" I mean "more secure". I think that both scripts have a security breach if the process is stopped while the file is still opened, but this has less chances to happen in the former script.

I don't think the languages matters but I mainly use Python.

4

2 に答える 2

0

Keeping aside all the other factors like

  • Securing the channel of data transfer

  • Checking the file permissions

  • Checking the file attributes so that application can trust the file

  • Secure Design

  • Time of Check Versus Time of Use for temporary files

    etc etc

If you want to pickup preference between just two opening the file once or opening the file multiple times for a operation.

My pick would be open the file only once. The more times you open a file the more time you will have to go through ensuring security checks.

于 2013-02-19T06:35:18.180 に答える
0

通常opencloseファイルは一度だけ必要です。主な理由はパフォーマンスです。「セキュリティ」が心配な場合は、スクリプトの予期しない終了について言及します。これを代わりに「安定性の問題」と呼びます。次にflush、スクリプトに書き込むたびにスクリプトを閉じますが、閉じないでください。次に、スクリプトが書き込んだコンテンツを救済した場合でも、ファイルはクリーンアップ中に閉じられます。

この戦略の利点は、スクリプト全体で何度も何度も行うのではなく、スクリプトにアクセスして開くことが成功したことを一度だけ確認する必要があることです。

于 2013-02-19T06:12:32.350 に答える