Prevent a file being written to more than once without file:close()

python close file
python close file after with open
file locking in c
how to write output to a file in python
python write to file
file locking in unix
python with open close required
python append to file

I'm currently working on a logging system. My problems arise when using for loops and file writing. Here is a small example:

file = io.open("text.txt","a") --text.txt can be literally anything
for i=1,8 do
  if x == true then
    file:write("X is true.")
  elseif y == true then
    file:write("Y is true.")
  end
end

Is there a way to stop the file from being written to multiple times without using file:close()? I have a huge number of different file:write sections, and adding file:close() after all of them would be a massive problem.

If file:close() every time is a massive problem, then this is the custom logic you need.

myFileMetatable = {}  --implement all necessary file operations here
function myFileMetatable.write(self, str)
    if not self.written then
        self.written = true
        self.f:write(str)
    end
end
function myFileMetatable.close(self)
    self.f:close()
end

myFile = {}
function myFile.open(filename, mode)
    local t = {f = io.open(filename, mode)}
    setmetatable(t, {__index = myFileMetatable})
    return t
end

--now you can do
file = myFile.open("test", "w")
file:write("test")
file:write("hello")
file:write("world")
file:close()    --and only "test" will be written

Note that this is probably much better than replacing file:write(str) with something file_write(file, str), since you need to store somewhere the fact that the file has already been written to, which you cannot store inside the FILE* object and using a global variable for that will break when using multiple files. That's why I wrap the FILE* object in a table and use myFileMetatable to implement my own methods that I will need.

However, if you need just one file at a time and don't mind the global variable then this is more efficient.

file_written = false
function file_write(file, str)
    if not file_written then
        file_written = true
        file:write(str)
    end
end

file = io.open("test", "w")
file_write(file, "test")
file_write(file, "hello")
file_write(file, "world")
file:close()

Mind that it's not as pretty as the first example and you might face a problem in the future, if you decide to expand beyond one file.

Beginning COBOL for Programmers, EXTEND Opening a file does not transfer any data to the record buffer; it simply not being written to the file or users being prevented from accessing the file. the CLOSE metalanguage indicate that you may specify more than one file name. File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it in a specific time and to prevent reading of the file while it's being modified or deleted.

How Egor Skriptunoff already said, I'll recommend you to write your own writing function. I'm normally using sth. like this:

local function writeFile(filePath, str)
  local outfile = io.open(filePath, 'w')
  outfile:write(str)
  outfile:close()
end

For appending to the file easily change the mode from w to a.

FileMaker Pro 9 Bible, To close a file, select its window (if you have more than one file or window open in it is possible that some data held in cache may not have been written to disk. Fortunately, this is an extremely rare occurrence; however, you should avoid� That'll prevent the file from being opened by any other process. FileShare.Write or FileShare.ReadWrite should allow the other process (subject to permissions) to open and write to the file while you are reading it, however you'll have to watch for the file changing underneath you while you read it - simply buffering the contents upon opening may help here.

For my specific case, I've found a solution - since I just want a single option to print, and it's the last option (rather than the first, and I should've specified this), I can just set a variable to what I want my output to be and write that at the end.

log = ""
if x == 2 then
  log = "X is 2."
elseif y == 2 then
  log = "Y is 2."
end
file:write(log)

For the last option, I'd refer anyone to the accepted answer which should be perfect.

The Weekly Underwriter, averred by them that it was not the insurance companies , but and to ture is to relieve the Attorney - General from the labor of visiting Senate File No . by the United States war revenue insurance has been written on not less than 200 risks in A contract of insurance is an agreement by which one amount of capital stock� Instead, it returns its cached version from sys.modules without executing any of its code. However there are several pitfalls worth noting: Importing the main module as an ordinary module effectively creates two instances of the same module under different names.

If you don't use "with", when does Python close files? The answer is , However, once Python exits from the “with” block, the file is automatically closed. Thus, by using “with”, you avoid the need to explicitly close files. while also trying to teach many other topics, is more than students can absorb. My experiment consisted of opening a file, writing some data to it, deleting� The end='' is to prevent Python from adding an additional newline to the text that is being printed and only print what is being read from the file. Now let’s dive into writing files. As with reading files, file objects have multiple methods that are useful for writing to a file:

File locking, File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it in a specific time and to prevent reading of the file while it's being modified or deleted. Systems implement locking to prevent the classic interceding update scenario Note that the region of the file being locked is not required� Let's say we have a file - the one to be used with multiple processes. I start with an assumption that file gets Write locked to get changed. If that is not the case for you, then my approach will not work. So if it sounds reasonable for you, then see the solution.

The Independent, This is so simple and fascinating that once started , I don ' t want to stop . med by the Independent Corporation when I volunteered to write this story of my Experience is nothing more than the remembered lessons of the days we have lived . He turned to a correspondence file close evening , and if given half a chance� Myth: Disabling the Page File Improves Performance. Some people will tell you that you should disable the page file to speed up your computer. The thinking goes like this: the page file is slower than RAM, and if you have enough RAM, Windows will use the page file when it should be using RAM, slowing down your computer.

Comments
  • Use break to exit the loop prematurely. Or replace file:write() with your own file_write() and implement your logic inside.
  • Wouldn't this still have the same problem as it opens the file multiple times?
  • Yes, in this case I'll recommend you to use the solution of IsawU. I misunderstand your question.