File.Open, Write and Save

File.open, write and save?

This turned out to be the best solution.

File.open("linecount.txt",'w') do |filea|
File.open("testfile.txt",'r') do |fileb|
while line = fileb.gets
filea.puts line.length
end
end
end

open() in Python does not create a file if it doesn't exist

You should use open with the w+ mode:

file = open('myfile.dat', 'w+')

How to write to a file which is open?

You can't really solve this because the problem is not with openpyxl per-se, rather with the file you manually opened. If you would have opened it as a Read-Only file, you will not get that error. Of course, you can't (easily) solve that programmatically as openpyxl is not aware of the open instances of Excel you have running in the background.

Note that when opening the file as read-only, you will not see the saved changes from openpyxl.

One possible workaround, to avoid losing your changes you were about to save, is to allow the user to close that instance of Excel and try to save again. Something like:

while True:
try:
wb.save(path)
except PermissionError:
input(f"Please close the excel {path} and press Enter")
else:
print(f"Excel file saved successfully at - {path}")
break

Alternatively save to a temporary file and let the user merge later:

from pathlib import Path

try:
wb.save(path)
except PermissionError:
path = Path(path)
temp_path = path.with_name(f"{path.stem}_temp{path.suffix}")
wb.save(temp_path)
print(f"Excel file saved temporarily at - {temp_path}")
else:
print(f"Excel file saved successfully at - {path}")

Warning: these might cover-up other possible PermissionErrors, so use with care.

Python beginner - Writing text file - problem: information doesn't save when opening with 'r+'

The problem is that you are using open with the argument 'r+' while what you want to use is 'a' or 'a+'.

opening a file in 'r+' will open file at the beginning and writing will overwrite lines instead of appending. that is why you should use 'a' or 'a+' as it writes new lines at the end of the file.

from: http://www.manpagez.com/man/3/fopen/

``r''   Open text file for reading.  The stream is positioned at the
beginning of the file.

``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.

``w'' Truncate to zero length or create text file for writing. The
stream is positioned at the beginning of the file.

``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.

``a'' Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.

``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

Correct way to write line to file?

This should be as simple as:

with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

  • The with statement
  • open()
    • 'a' is for append, or use
    • 'w' to write with truncation
  • os (particularly os.linesep)


Related Topics



Leave a reply



Submit