Change a file type in Python?

E

Eamonn Rea

When opening a file, you'd say whether you want to read or write to a file.This is fine, but say for example later on in the program I change my mindand I want to write to a file instead of reading it. Yes, I could just say'r+w' when opening the file, but what if I don't know if I'm going to do both? What if I have the user decide, and then later on I let the user change this.

Is it possible to do so without opening the file again and using the same file object?

Thanks!
 
C

Chris Angelico

Is it possible to do so without opening the file again and using the same file object?

In the general sense, no, but you may be able to abuse things terribly
by calling __init__ on an existing object. The only advantage of that
would be if you have multiple references to the file object, so
normally don't - just close it and reopen. You can't change
access/share mode on the file system without closing and reopening, so
ultimately that's going to have to happen.

As a separate point, can you please use a better client than Google
Groups? It's buggy and your posts come out looking ugly. There are
other news clients, or you can sign up for the email list here:

https://mail.python.org/mailman/listinfo/python-list

ChrisA
 
S

Steven D'Aprano

When opening a file, you'd say whether you want to read or write to a
file. This is fine, but say for example later on in the program I change
my mind and I want to write to a file instead of reading it. Yes, I
could just say 'r+w' when opening the file, but what if I don't know if
I'm going to do both? What if I have the user decide, and then later on
I let the user change this.

I'd say if you're worried about this, your program needs to be redesigned.

In general, with the exception of special purpose files like databases
(and you're not inventing your own database, I hope) it is good clean
programming practice to keep files open only so long as you really need
them to be open.

- It's only possible to have open some number of files open at a
time. That number is typically quite large, but not *that* large.
Every time you open a file and keep it open, it impacts other
programs and the operating system by a small amount.

- Particularly on Windows, once you open a file, nothing else can
open it. That means it can't be backed up, scanned for viruses,
opened by other programs, deleted or renamed.

- When you open a file for writing, and keep it open, the changes
you make aren't guaranteed to be written to disk until you
actually close the file. You can call the sync method, the
longer you keep it open the more likely the risk of data-loss in
the case of sudden crash or power interruption.

- To avoid data loss, you should try to avoid updating files in
place. If the program crashes, you could leave the file in a
messed up state.


With very few exceptions, I recommend that you avoid this approach:

# Don't do this.
open file
read data
process in memory
write changes to file
more processing
write changes to file
more processing
write changes to file
close file
exit

in favour of this approach:

open file; read data; close file
process in memory
open file; write to file; close file
more processing
open file; write to file; close file
more processing
open file; write to file; close file
exit

Is it possible to do so without opening the file again and using the
same file object?

No. You cannot even re-open a file object using the same file mode. Why
do you care? It isn't difficult to throw away the file object and create
a new one. That part is cheap.
 
R

rusi

Thanks for the help!

Ok, I'll look into the mailing list.

[Assuming you are using GG with firefox on linux]

All you need to do is
1. Install 'Its all text' FF addon
2. Point the 'editor' of 'Its all text' to the below python script

After that, a small new edit button will appear outside the text-box and its one-click solution

-------------Python Script--------------
#!/usr/bin/env python3

# As far as I know both python2 and 3 work
# Windows/Mac no idea :)

# A script to drop-in as an editor for firefox addon "Its all text"
# It cleans up two google-group nuisances:
# 1. Useless blank lines
# 2. Excessively long lines
# No efforts at error reporting as stderr is not available in any
# easy way (I know) to firefox (other browsers?)
# To test separately:
# Compose a mail (preferably reply) in GG
# Copy-paste the stuff (maybe with some long lines added without the >)
# Run this script with that filename as argv[1]

from sys import argv
from re import sub
import re

# Clean double spacing
def cleands(s):
# Assumption: ASCII 025 (NAK) never occurs in input
s1 = sub("^> *\n> *$", "\025" , s , flags=re.M)
s2 = sub("^> *\n" , "" , s1, flags=re.M)
s3 = sub("\025\n" , ">\n" , s2, flags=re.M)
return s3

# Maximum length that (new) lines should attain
Maxlen = 75

# clean all long lines, s is the whole file/text
def cleanall_ll(s):
lines = (cleanll(l) for l in s.split("\n"))
return "\n".join(lines)

# clean one long line
def cleanll(line):
return ( line if line.startswith(">") else cleanll_rec(line) )

def cleanll_rec(line):
if len(line) <= Maxlen : return line
pos = line.rfind(" ", 0, Maxlen)
if pos == -1 : #Failed due to no spaces
return line
return line[0:pos] + "\n" + cleanll_rec(line[pos+1: ])

def clean(s):
return cleanall_ll(cleands(s))

def main():
with open(argv[1]) as f: s = f.read()
with open(argv[1], "w") as f: f.write(clean(s))

if __name__ == '__main__' :
main()
 
C

Chris Angelico

Thanks for the help!

Ok, I'll look into the mailing list.

[Assuming you are using GG with firefox on linux]

All you need to do is
1. Install 'Its all text' FF addon
2. Point the 'editor' of 'Its all text' to the below python script

After that, a small new edit button will appear outside the text-box and its one-click solution

Yeah I still think it's a lot easier to switch to a properly-working
system. What you're suggesting still doesn't wrap text properly, as
evidenced by your above over-long line.

ChrisA
 
R

rusi

Thanks for the help!

Ok, I'll look into the mailing list.

[Assuming you are using GG with firefox on linux]

All you need to do is
1. Install 'Its all text' FF addon
2. Point the 'editor' of 'Its all text' to the below python script

After that, a small new edit button will appear outside the text-box and its one-click solution

What you're suggesting still doesn't wrap text properly, as
evidenced by your above over-long line.

ChrisA

Ok my bad. I offered a 1-click solution, but did 0 clicks :)
Strictly speaking one needs anywhere between one and two clicks for this
to work properly. My profuse apologies for the improper and illegitimate
round-down said:
Yeah I still think it's a lot easier to switch to a properly-working
system.

Of course -- if 1.something clicks are too onerous, you are free not to use
it :)

More seriously this discussion completely misses the point.

I think we are dealing with 3 completely separable problems:
[Slightly changing what I earlier wrote…]

1. Undesirable elements -- spam, troll and more exotic
2. Immature noobs -- literally or almost literally kids
3. Stupid technology -- in this case, GG

The anti-GG crusade is getting pissed-off with 1 and/or 2 and then
attacking 3.
 
C

Chris Angelico

I think we are dealing with 3 completely separable problems:
[Slightly changing what I earlier wrote…]

1. Undesirable elements -- spam, troll and more exotic
2. Immature noobs -- literally or almost literally kids
3. Stupid technology -- in this case, GG

The anti-GG crusade is getting pissed-off with 1 and/or 2 and then
attacking 3.

Most of it is getting annoyed at the results of 3, and then attacking
3. That's what I do, at least. There have been several people who've
switched to email as a result of being told that their posts are
coming out looking ugly; their posts subsequently are NOT ugly, and
they always had useful content in them, so they become productive and
highly welcome members of the community without being masked behind
buggy technology. Nothing to do with immaturity or spam.

ChrisA
 
S

Steven D'Aprano

Most of it is getting annoyed at the results of 3, and then attacking 3.

I know the feeling. I've never trusted 3, I've always felt that it's
plotting something. And it looks like half an 8, but it's not. What's
with that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top