Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #107373 > unrolled thread

Python path and append

Started bySeymore4Head <Seymore4Head@Hotmail.invalid>
First post2016-04-19 18:29 -0400
Last post2016-04-26 10:25 +1000
Articles 20 on this page of 27 — 15 participants

Back to article view | Back to comp.lang.python


Contents

  Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-19 18:29 -0400
    Re: Python path and append Chris Angelico <rosuav@gmail.com> - 2016-04-20 08:38 +1000
    Re: Python path and append Matthew Barnett <mrabarnett@mrabarnett.plus.com> - 2016-04-20 00:36 +0100
    Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-25 14:10 -0400
      Re: Python path and append Rob Gaddi <rgaddi@highlandtechnology.invalid> - 2016-04-25 18:24 +0000
        Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-25 15:00 -0400
          RE: Python path and append Joaquin Alzola <Joaquin.Alzola@lebara.com> - 2016-04-25 19:08 +0000
            Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-25 16:15 -0400
              Re: Python path and append Random832 <random832@fastmail.com> - 2016-04-25 16:28 -0400
              Re: Python path and append Peter Otten <__peter__@web.de> - 2016-04-25 23:38 +0200
              Re: Python path and append Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-04-25 19:57 -0400
          Re: Python path and append Rob Gaddi <rgaddi@highlandtechnology.invalid> - 2016-04-25 19:31 +0000
          Re: Python path and append MRAB <python@mrabarnett.plus.com> - 2016-04-25 20:44 +0100
            Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-25 16:43 -0400
          Re: Python path and append Steven D'Aprano <steve@pearwood.info> - 2016-04-26 11:51 +1000
            Re: Python path and append Dan Sommers <dan@tombstonezero.net> - 2016-04-26 01:59 +0000
            Re: Python path and append Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2016-04-26 18:23 +1200
            Re: Python path and append boB Stepp <robertvstepp@gmail.com> - 2016-04-29 15:26 -0500
              Re: Python path and append Steven D'Aprano <steve@pearwood.info> - 2016-04-30 11:44 +1000
      Re: Python path and append John Gordon <gordon@panix.com> - 2016-04-25 21:26 +0000
        Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-25 18:04 -0400
          Re: Python path and append Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-04-25 20:03 -0400
          Re: Python path and append Steven D'Aprano <steve@pearwood.info> - 2016-04-26 11:53 +1000
            Re: Python path and append Seymore4Head <Seymore4Head@Hotmail.invalid> - 2016-04-26 22:56 -0400
              Re: Python path and append Chris Angelico <rosuav@gmail.com> - 2016-04-27 13:06 +1000
              Re: Python path and append Stephen Hansen <me+python@ixokai.io> - 2016-04-27 17:24 -0700
        Re: Python path and append Chris Angelico <rosuav@gmail.com> - 2016-04-26 10:25 +1000

Page 1 of 2  [1] 2  Next page →


#107373 — Python path and append

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2016-04-19 18:29 -0400
SubjectPython path and append
Message-ID<smbdhb5kjje2oandna4vj5udku9gh1h9oa@4ax.com>
This doesn't work.  Does Python recognize hidden directories?

handle = open("\\Winmx\New$\q.txt")
for line in handle:
    line=line.strip()
    print line

    
Traceback (most recent call last):
  File "\\Winmx\New$\add viewed.py", line 2, in <module>
    handle = open("\\Winmx\New$\q.txt")
IOError: [Errno 2] No such file or directory: '\\Winmx\\New$\\q.txt'

What I would like to do is read a plain text file from a hidden
network drive and append a space and the * character to the end of
each line.

Would someone be so kind as to fill in the blanks to accomplish this
please?

[toc] | [next] | [standalone]


#107374

FromChris Angelico <rosuav@gmail.com>
Date2016-04-20 08:38 +1000
Message-ID<mailman.44.1461105533.30862.python-list@python.org>
In reply to#107373
On Wed, Apr 20, 2016 at 8:29 AM, Seymore4Head
<Seymore4Head@hotmail.invalid> wrote:
>
> handle = open("\\Winmx\New$\q.txt")
> for line in handle:
>     line=line.strip()
>     print line
>
>
> Traceback (most recent call last):
>   File "\\Winmx\New$\add viewed.py", line 2, in <module>
>     handle = open("\\Winmx\New$\q.txt")
> IOError: [Errno 2] No such file or directory: '\\Winmx\\New$\\q.txt'
>
> What I would like to do is read a plain text file from a hidden
> network drive and append a space and the * character to the end of
> each line.

Start with this:

print("\\Winmx\New$\q.txt")

If that doesn't do what you expect, it's possibly because you want to
use a raw string literal to prevent the backslashes from being parsed.

handle = open(r"\\Winmx\New$\q.txt")

That might help you.

(One clue that this is happening is that some of your backslashes got
doubled in the error message.)

ChrisA

[toc] | [prev] | [next] | [standalone]


#107380

FromMatthew Barnett <mrabarnett@mrabarnett.plus.com>
Date2016-04-20 00:36 +0100
Message-ID<mailman.5.1461110859.12923.python-list@python.org>
In reply to#107373
On 2016-04-19 23:38, Chris Angelico wrote:
> On Wed, Apr 20, 2016 at 8:29 AM, Seymore4Head
> <Seymore4Head@hotmail.invalid> wrote:
>>
>> handle = open("\\Winmx\New$\q.txt")
>> for line in handle:
>>     line=line.strip()
>>     print line
>>
>>
>> Traceback (most recent call last):
>>   File "\\Winmx\New$\add viewed.py", line 2, in <module>
>>     handle = open("\\Winmx\New$\q.txt")
>> IOError: [Errno 2] No such file or directory: '\\Winmx\\New$\\q.txt'
>>
>> What I would like to do is read a plain text file from a hidden
>> network drive and append a space and the * character to the end of
>> each line.
>
> Start with this:
>
> print("\\Winmx\New$\q.txt")
>
> If that doesn't do what you expect, it's possibly because you want to
> use a raw string literal to prevent the backslashes from being parsed.
>
> handle = open(r"\\Winmx\New$\q.txt")
>
> That might help you.
>
> (One clue that this is happening is that some of your backslashes got
> doubled in the error message.)
>
when printed out:

 >>> print "\\Winmx\New$\q.txt"
\Winmx\New$\q.txt

That's a file 2 directories down on the current drive.

[toc] | [prev] | [next] | [standalone]


#107620

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2016-04-25 14:10 -0400
Message-ID<27nshbp40p1llr231dqm31p754tvurkb8i@4ax.com>
In reply to#107373
On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
<Seymore4Head@Hotmail.invalid> wrote:

I am going to forget using a directory path.
I would like to take the file win.txt and append a space and the *
symbol.

f = open('win.txt', 'r+')
for line in f:
    f.read(line)
    f.write(line+" *")

This doesn't work.  Would someone fix it please?  It is for a task I
am trying to accomplish just for a home task.

[toc] | [prev] | [next] | [standalone]


#107621

FromRob Gaddi <rgaddi@highlandtechnology.invalid>
Date2016-04-25 18:24 +0000
Message-ID<nflnc1$7a4$1@dont-email.me>
In reply to#107620
Seymore4Head wrote:

> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
> <Seymore4Head@Hotmail.invalid> wrote:
>
> I am going to forget using a directory path.
> I would like to take the file win.txt and append a space and the *
> symbol.
>
> f = open('win.txt', 'r+')
> for line in f:
>     f.read(line)
>     f.write(line+" *")
>
> This doesn't work.  Would someone fix it please?  It is for a task I
> am trying to accomplish just for a home task.

"for line in f:" already means "make the variable line equal to each
line in f sequentially".  f.read is both superfluous and also doesn't do
that.  Leave it out entirely.

The next problem you'll have is that iterating over the lines of the
file leaves the newline at the end of line, so your * will end up on the
wrong line.

Do yourself a favor: https://docs.python.org/3/tutorial/inputoutput.html
isn't very long.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com

Email address domain is currently out of order.  See above to fix.

[toc] | [prev] | [next] | [standalone]


#107622

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2016-04-25 15:00 -0400
Message-ID<n5qshb5tmq4gk6nvqmad44lb523ouoiji5@4ax.com>
In reply to#107621
On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi
<rgaddi@highlandtechnology.invalid> wrote:

>Seymore4Head wrote:
>
>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>> <Seymore4Head@Hotmail.invalid> wrote:
>>
>> I am going to forget using a directory path.
>> I would like to take the file win.txt and append a space and the *
>> symbol.
>>
>> f = open('win.txt', 'r+')
>> for line in f:
>>     f.read(line)
>>     f.write(line+" *")
>>
>> This doesn't work.  Would someone fix it please?  It is for a task I
>> am trying to accomplish just for a home task.
>
>"for line in f:" already means "make the variable line equal to each
>line in f sequentially".  f.read is both superfluous and also doesn't do
>that.  Leave it out entirely.
>
>The next problem you'll have is that iterating over the lines of the
>file leaves the newline at the end of line, so your * will end up on the
>wrong line.
>
>Do yourself a favor: https://docs.python.org/3/tutorial/inputoutput.html
>isn't very long.

I was reading that.  I have read it before.  I don't use python enough
to even remember the simple stuff.  Then when I try to use if for
something simple I forget how.

f = open('wout.txt', 'r+')
for line in f:
    line=line.strip()
    f.write(line+" *")
f.close()

Still broke.  How about just telling me where I missed?  Please?

[toc] | [prev] | [next] | [standalone]


#107623

FromJoaquin Alzola <Joaquin.Alzola@lebara.com>
Date2016-04-25 19:08 +0000
Message-ID<mailman.89.1461611345.32212.python-list@python.org>
In reply to#107622
Strip() = white spaces.
Description
The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).

Use to remove return carriage--> line[:-1]

-----Original Message-----
From: Python-list [mailto:python-list-bounces+joaquin.alzola=lebara.com@python.org] On Behalf Of Seymore4Head
Sent: 25 April 2016 20:01
To: python-list@python.org
Subject: Re: Python path and append

On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi <rgaddi@highlandtechnology.invalid> wrote:

>Seymore4Head wrote:
>
>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>> <Seymore4Head@Hotmail.invalid> wrote:
>>
>> I am going to forget using a directory path.
>> I would like to take the file win.txt and append a space and the *
>> symbol.
>>
>> f = open('win.txt', 'r+')
>> for line in f:
>>     f.read(line)
>>     f.write(line+" *")
>>
>> This doesn't work.  Would someone fix it please?  It is for a task I
>> am trying to accomplish just for a home task.
>
>"for line in f:" already means "make the variable line equal to each
>line in f sequentially".  f.read is both superfluous and also doesn't
>do that.  Leave it out entirely.
>
>The next problem you'll have is that iterating over the lines of the
>file leaves the newline at the end of line, so your * will end up on
>the wrong line.
>
>Do yourself a favor:
>https://docs.python.org/3/tutorial/inputoutput.html
>isn't very long.

I was reading that.  I have read it before.  I don't use python enough to even remember the simple stuff.  Then when I try to use if for something simple I forget how.

f = open('wout.txt', 'r+')
for line in f:
    line=line.strip()
    f.write(line+" *")
f.close()

Still broke.  How about just telling me where I missed?  Please?
--
https://mail.python.org/mailman/listinfo/python-list
This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.

[toc] | [prev] | [next] | [standalone]


#107626

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2016-04-25 16:15 -0400
Message-ID<02ushb9mntvtedeg5c7l33uhapt2j6nivu@4ax.com>
In reply to#107623
Thanks for the tip.

Still broke.  :(

f = open('wout.txt', 'r+')
for line in f:
    if line=="":
        exit
    line=line[:-1]
    line=line+" *"
    f.write(line)
    print line
f.close()



I did notice that it wrote the 3 lines of test file but it didn't
append the * after the third entry and it starts printing garbage
after that.


On Mon, 25 Apr 2016 19:08:56 +0000, Joaquin Alzola
<Joaquin.Alzola@lebara.com> wrote:

>Strip() = white spaces.
>Description
>The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
>
>Use to remove return carriage--> line[:-1]
>
>-----Original Message-----
>From: Python-list [mailto:python-list-bounces+joaquin.alzola=lebara.com@python.org] On Behalf Of Seymore4Head
>Sent: 25 April 2016 20:01
>To: python-list@python.org
>Subject: Re: Python path and append
>
>On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi <rgaddi@highlandtechnology.invalid> wrote:
>
>>Seymore4Head wrote:
>>
>>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>>> <Seymore4Head@Hotmail.invalid> wrote:
>>>
>>> I am going to forget using a directory path.
>>> I would like to take the file win.txt and append a space and the *
>>> symbol.
>>>
>>> f = open('win.txt', 'r+')
>>> for line in f:
>>>     f.read(line)
>>>     f.write(line+" *")
>>>
>>> This doesn't work.  Would someone fix it please?  It is for a task I
>>> am trying to accomplish just for a home task.
>>
>>"for line in f:" already means "make the variable line equal to each
>>line in f sequentially".  f.read is both superfluous and also doesn't
>>do that.  Leave it out entirely.
>>
>>The next problem you'll have is that iterating over the lines of the
>>file leaves the newline at the end of line, so your * will end up on
>>the wrong line.
>>
>>Do yourself a favor:
>>https://docs.python.org/3/tutorial/inputoutput.html
>>isn't very long.
>
>I was reading that.  I have read it before.  I don't use python enough to even remember the simple stuff.  Then when I try to use if for something simple I forget how.
>
>f = open('wout.txt', 'r+')
>for line in f:
>    line=line.strip()
>    f.write(line+" *")
>f.close()
>
>Still broke.  How about just telling me where I missed?  Please?

[toc] | [prev] | [next] | [standalone]


#107627

FromRandom832 <random832@fastmail.com>
Date2016-04-25 16:28 -0400
Message-ID<mailman.92.1461616116.32212.python-list@python.org>
In reply to#107626
On Mon, Apr 25, 2016, at 16:15, Seymore4Head wrote:
> Thanks for the tip.
> 
> Still broke.  :(
> 
> f = open('wout.txt', 'r+')
> for line in f:
>     if line=="":
>         exit
>     line=line[:-1]
>     line=line+" *"
>     f.write(line)
>     print line
> f.close()

Your problem is that after you read the first line, your file "cursor"
is positioned after the end of that line. So when you write the modified
version of the line, it ends up after that. And then when you write it,
the cursor is wherever the end of that is.

So if you start with this:
AAA
BBB
CCC

You'll end up with this:
AAA
AAA* [this overwrites "BBB_C" with "AAA*_" if _ is the line break]
CC
CC*

There's no good way around this. You can either read the whole file into
memory at once into a list, then rewind (look at the seek function) and
write the lines out of the list, or you can write to a *different* file
than the one you're reading.

[toc] | [prev] | [next] | [standalone]


#107631

FromPeter Otten <__peter__@web.de>
Date2016-04-25 23:38 +0200
Message-ID<mailman.94.1461620307.32212.python-list@python.org>
In reply to#107626
Random832 wrote:

> On Mon, Apr 25, 2016, at 16:15, Seymore4Head wrote:
>> Thanks for the tip.
>> 
>> Still broke.  :(
>> 
>> f = open('wout.txt', 'r+')
>> for line in f:
>>     if line=="":
>>         exit
>>     line=line[:-1]
>>     line=line+" *"
>>     f.write(line)
>>     print line
>> f.close()
> 
> Your problem is that after you read the first line, your file "cursor"
> is positioned after the end of that line. So when you write the modified
> version of the line, it ends up after that. And then when you write it,
> the cursor is wherever the end of that is.
> 
> So if you start with this:
> AAA
> BBB
> CCC
> 
> You'll end up with this:
> AAA
> AAA* [this overwrites "BBB_C" with "AAA*_" if _ is the line break]
> CC
> CC*
> 
> There's no good way around this. You can either read the whole file into
> memory at once into a list, then rewind (look at the seek function) and
> write the lines out of the list, or you can write to a *different* file
> than the one you're reading.

You can leave the details to python though:

$ cat sample.txt
alpha
beta
gamma
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fileinput
>>> for line in fileinput.input("sample.txt", inplace=True):
...     print line.rstrip("\n"), "*"
... 
>>> 
$ cat sample.txt 
alpha *
beta *
gamma *

Too much magic for my taste, but the OP might like it.

[toc] | [prev] | [next] | [standalone]


#107633

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2016-04-25 19:57 -0400
Message-ID<mailman.95.1461628677.32212.python-list@python.org>
In reply to#107626
On Mon, 25 Apr 2016 16:15:15 -0400, Seymore4Head
<Seymore4Head@Hotmail.invalid> declaimed the following:

>Thanks for the tip.
>
>Still broke.  :(
>
>f = open('wout.txt', 'r+')
>for line in f:
>    if line=="":
>        exit
>    line=line[:-1]
>    line=line+" *"
>    f.write(line)
>    print line
>f.close()
>
>
>
>I did notice that it wrote the 3 lines of test file but it didn't
>append the * after the third entry and it starts printing garbage
>after that.
>

	Unless Python (or the C runtime) have implement Xerox CP/V "UPDATE"
file mode*, after the first line is read, the I/O pointer is located at the
end of that line. You now attempt to write the modified line, which will
overwrite parts of the second line (note that you are not writing
new-lines). After that write, you are positioned at some point unknown
(relatively speaking, and do a read operation starting at where the write
ended.

	Any I/O operation that changes the length of the data is going to fail,
even if you reposition (look up "seek()" and "tell()")

	On Windows, where the physical line-ending is <cr><lf>, but gets
transformed to just <lf> by Python text reads, you are stripping the <lf>,
adding " *". If the next record is the same length, that " *" on write will
replace the <cr><lf> pair.

	For the type of operation you are performing, on text files, you really
need to go through the hassle of renames and copies... That is, rename the
input file to some temporary name, open it for read, open the original name
for write, and then read input, modify, write output...

	OR -- if the files are short enough, just read the entire file, and
process it in memory...

fupdate = open("theFile.txt", "r+")
fdata = fupdate.readlines()
#	doing piecemeal, rather than making a one-liner
for l, ln in enumerate(fdata):
	#	strip new-line IF present
	if ln[-1] == "\n":
		ln = ln[:-1]
	fdata[l] = ln + " *"
#	join new data with newline
fdata = "\n".join(fdata)
#rewind the file
fupdate.seek(0)
fupdate.write(fdata)
fupdate.close()






* UPDATE mode maintained two I/O pointers: a read pointer and write
pointer, and required one to read one or more records before doing a write
operation. As long as the data (record) size did not change it allowed for
Read/Modify/Write of records.
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#107624

FromRob Gaddi <rgaddi@highlandtechnology.invalid>
Date2016-04-25 19:31 +0000
Message-ID<nflraf$qb0$1@dont-email.me>
In reply to#107622
Seymore4Head wrote:

> On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi
> <rgaddi@highlandtechnology.invalid> wrote:
>
>>Seymore4Head wrote:
>>
>>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>>> <Seymore4Head@Hotmail.invalid> wrote:
>>>
>>> I am going to forget using a directory path.
>>> I would like to take the file win.txt and append a space and the *
>>> symbol.
>>>
>>> f = open('win.txt', 'r+')
>>> for line in f:
>>>     f.read(line)
>>>     f.write(line+" *")
>>>
>>> This doesn't work.  Would someone fix it please?  It is for a task I
>>> am trying to accomplish just for a home task.
>>
>>"for line in f:" already means "make the variable line equal to each
>>line in f sequentially".  f.read is both superfluous and also doesn't do
>>that.  Leave it out entirely.
>>
>>The next problem you'll have is that iterating over the lines of the
>>file leaves the newline at the end of line, so your * will end up on the
>>wrong line.
>>
>>Do yourself a favor: https://docs.python.org/3/tutorial/inputoutput.html
>>isn't very long.
>
> I was reading that.  I have read it before.  I don't use python enough
> to even remember the simple stuff.  Then when I try to use if for
> something simple I forget how.
>
> f = open('wout.txt', 'r+')
> for line in f:
>     line=line.strip()
>     f.write(line+" *")
> f.close()
>
> Still broke.  How about just telling me where I missed?  Please?

Depends on what "broke" means.  I'm going to go out on a limb and guess
that the problem now is that you get no newlines at all, because they've
been stripped off of the line you read and .write doesn't put it back
on, in which case you should be adding " *\n" instead.  If that's not
it, then reply hazy, please concentrate and ask again.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com

Email address domain is currently out of order.  See above to fix.

[toc] | [prev] | [next] | [standalone]


#107625

FromMRAB <python@mrabarnett.plus.com>
Date2016-04-25 20:44 +0100
Message-ID<mailman.90.1461613684.32212.python-list@python.org>
In reply to#107622
On 2016-04-25 20:08, Joaquin Alzola wrote:
> Strip() = white spaces.
> Description
> The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
>
> Use to remove return carriage--> line[:-1]
>
1. In the file it might be a linefeed, or a carriage return, or a
carriage return followed by a linefeed, depending on the operating
system. Python translates it to a linefeed "\n" (or 'newline') on
reading.

2. It's possible that the last line doesn't end have a line ending, so
line[:-1] could be removing some other character. It's safer to use
line.rstrip("\n").

> -----Original Message-----
> From: Python-list [mailto:python-list-bounces+joaquin.alzola=lebara.com@python.org] On Behalf Of Seymore4Head
> Sent: 25 April 2016 20:01
> To: python-list@python.org
> Subject: Re: Python path and append
>
> On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi <rgaddi@highlandtechnology.invalid> wrote:
>
>>Seymore4Head wrote:
>>
>>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>>> <Seymore4Head@Hotmail.invalid> wrote:
>>>
>>> I am going to forget using a directory path.
>>> I would like to take the file win.txt and append a space and the *
>>> symbol.
>>>
>>> f = open('win.txt', 'r+')
>>> for line in f:
>>>     f.read(line)
>>>     f.write(line+" *")
>>>
>>> This doesn't work.  Would someone fix it please?  It is for a task I
>>> am trying to accomplish just for a home task.
>>
>>"for line in f:" already means "make the variable line equal to each
>>line in f sequentially".  f.read is both superfluous and also doesn't
>>do that.  Leave it out entirely.
>>
>>The next problem you'll have is that iterating over the lines of the
>>file leaves the newline at the end of line, so your * will end up on
>>the wrong line.
>>
>>Do yourself a favor:
>>https://docs.python.org/3/tutorial/inputoutput.html
>>isn't very long.
>
> I was reading that.  I have read it before.  I don't use python enough to even remember the simple stuff.  Then when I try to use if for something simple I forget how.
>
> f = open('wout.txt', 'r+')
> for line in f:
>     line=line.strip()
>     f.write(line+" *")
> f.close()
>
> Still broke.  How about just telling me where I missed?  Please?
> --
> https://mail.python.org/mailman/listinfo/python-list
> This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.
>

[toc] | [prev] | [next] | [standalone]


#107629

FromSeymore4Head <Seymore4Head@Hotmail.invalid>
Date2016-04-25 16:43 -0400
Message-ID<280thb5v16q1ids78j6rbbcs95957osgja@4ax.com>
In reply to#107625
I am using a test file that is only 3 lines:
Punjabi .Mp3
Big Lake (DVD) SWV.avi
Blue Balloon.AHC.RH.mkv

The program correctly appends an * to the end of the line, but then it
goes into a loop printing random looking stuff.

f = open('wout.txt', 'r+')
for line in f:
    if line=="":
        exit
    line=line[:-1]
    line=line+" *"
    f.write(line)
    print line
f.close()


On Mon, 25 Apr 2016 20:44:50 +0100, MRAB <python@mrabarnett.plus.com>
wrote:

>On 2016-04-25 20:08, Joaquin Alzola wrote:
>> Strip() = white spaces.
>> Description
>> The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
>>
>> Use to remove return carriage--> line[:-1]
>>
>1. In the file it might be a linefeed, or a carriage return, or a
>carriage return followed by a linefeed, depending on the operating
>system. Python translates it to a linefeed "\n" (or 'newline') on
>reading.
>
>2. It's possible that the last line doesn't end have a line ending, so
>line[:-1] could be removing some other character. It's safer to use
>line.rstrip("\n").
>
>> -----Original Message-----
>> From: Python-list [mailto:python-list-bounces+joaquin.alzola=lebara.com@python.org] On Behalf Of Seymore4Head
>> Sent: 25 April 2016 20:01
>> To: python-list@python.org
>> Subject: Re: Python path and append
>>
>> On Mon, 25 Apr 2016 18:24:02 -0000 (UTC), Rob Gaddi <rgaddi@highlandtechnology.invalid> wrote:
>>
>>>Seymore4Head wrote:
>>>
>>>> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
>>>> <Seymore4Head@Hotmail.invalid> wrote:
>>>>
>>>> I am going to forget using a directory path.
>>>> I would like to take the file win.txt and append a space and the *
>>>> symbol.
>>>>
>>>> f = open('win.txt', 'r+')
>>>> for line in f:
>>>>     f.read(line)
>>>>     f.write(line+" *")
>>>>
>>>> This doesn't work.  Would someone fix it please?  It is for a task I
>>>> am trying to accomplish just for a home task.
>>>
>>>"for line in f:" already means "make the variable line equal to each
>>>line in f sequentially".  f.read is both superfluous and also doesn't
>>>do that.  Leave it out entirely.
>>>
>>>The next problem you'll have is that iterating over the lines of the
>>>file leaves the newline at the end of line, so your * will end up on
>>>the wrong line.
>>>
>>>Do yourself a favor:
>>>https://docs.python.org/3/tutorial/inputoutput.html
>>>isn't very long.
>>
>> I was reading that.  I have read it before.  I don't use python enough to even remember the simple stuff.  Then when I try to use if for something simple I forget how.
>>
>> f = open('wout.txt', 'r+')
>> for line in f:
>>     line=line.strip()
>>     f.write(line+" *")
>> f.close()
>>
>> Still broke.  How about just telling me where I missed?  Please?
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>> This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.
>>

[toc] | [prev] | [next] | [standalone]


#107636

FromSteven D'Aprano <steve@pearwood.info>
Date2016-04-26 11:51 +1000
Message-ID<571ec99c$0$1607$c3e8da3$5496439d@news.astraweb.com>
In reply to#107622
On Tue, 26 Apr 2016 05:00 am, Seymore4Head wrote:

> I was reading that.  I have read it before.  I don't use python enough
> to even remember the simple stuff.  Then when I try to use if for
> something simple I forget how.

It is perfectly fine to forget things that you read weeks or months before.
The point is, having forgotten it, you should go back and refresh your
memory when you need to.


> f = open('wout.txt', 'r+')
> for line in f:
>     line=line.strip()
>     f.write(line+" *")
> f.close()
> 
> Still broke.  How about just telling me where I missed?  Please?

The contents of files don't just magically get moved out of the way when you
write to them. There is no "insert mode" for files -- they are always set
to "overwrite" mode. (Possible a few very old operating systems on
supercomputers from the 1970s or 80s may have supported inserting... I seem
to recall that VMS may have allowed that... but don't quote me.)

So you can append to the *end* of a file without disrupting the content, but
you cannot insert to the middle or beginning of a file without overwriting.

The basic way to insert data into a file is:

* read the entire file into memory;
* insert the new data into the memory;
* write the entire file out again.



with open("myfile.txt") as f:
    lines = f.readlines()

for i, line in enumerate(lines):
    lines[i] = line.strip() + " *\n"  # space, asterisk, newline

with open("myfile.txt", "w") as f:
    f.writelines(lines)


That's good enough for DIY or hobby use. But for professional use, it starts
getting *very* complex quickly. What if the power goes off or your computer
crashes half-way through writing the file? You've lost all your data.

See here for the *start* of a more professional approach:

http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#107638

FromDan Sommers <dan@tombstonezero.net>
Date2016-04-26 01:59 +0000
Message-ID<nfmi2n$126$1@dont-email.me>
In reply to#107636
On Tue, 26 Apr 2016 11:51:23 +1000, Steven D'Aprano wrote:

> ... (Possible a few very old operating systems on supercomputers from
> the 1970s or 80s may have supported inserting... I seem to recall that
> VMS may have allowed that... but don't quote me.)

Some [non-supercomputer] OSes/filesystems/languages support(ed) the
notion of fixed-length records, where a file acted as if it were an
array of records.  You could, e.g., replace Record Number 3 without
disturbing Record Number 2 or Record Number 4.  In the systems I
remember like that, the records were simply ad hoc collections of
whatever you wrote, not unlike the arguments to print, and it was up to
your application to read and write the same structure.  The limitation,
of course, was that you had to declare the length up front, and that you
ended up with wasted space somewhere if a lot of your records were
"short."

[toc] | [prev] | [next] | [standalone]


#107641

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2016-04-26 18:23 +1200
Message-ID<do8fqqF7o8eU1@mid.individual.net>
In reply to#107636
Steven D'Aprano wrote:
> (Possible a few very old operating systems on
> supercomputers from the 1970s or 80s may have supported inserting... I seem
> to recall that VMS may have allowed that... but don't quote me.)

I wouldn't be surprised if VMS provided some sort of indexed
random-access file structure that supported inserting records.
OSes of that era tended to be big on things like that, since
they were all about Serious Data Processing.

But it probably wouldn't have let you insert data into the
middle of a sequential file without explicitly moving
everything that came after it.

-- 
Greg

[toc] | [prev] | [next] | [standalone]


#107864

FromboB Stepp <robertvstepp@gmail.com>
Date2016-04-29 15:26 -0500
Message-ID<mailman.228.1461961612.32212.python-list@python.org>
In reply to#107636
On Mon, Apr 25, 2016 at 8:51 PM, Steven D'Aprano <steve@pearwood.info> wrote:

> See here for the *start* of a more professional approach:
>
> http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/

What else would I need to know/consider in order to have a *complete*
professional approach?



-- 
boB

[toc] | [prev] | [next] | [standalone]


#107882

FromSteven D'Aprano <steve@pearwood.info>
Date2016-04-30 11:44 +1000
Message-ID<57240e15$0$1607$c3e8da3$5496439d@news.astraweb.com>
In reply to#107864
On Sat, 30 Apr 2016 06:26 am, boB Stepp wrote:

> On Mon, Apr 25, 2016 at 8:51 PM, Steven D'Aprano <steve@pearwood.info>
> wrote:
> 
>> See here for the *start* of a more professional approach:
>>
>>
http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/
> 
> What else would I need to know/consider in order to have a *complete*
> professional approach?

When I know, I'll tell you.

I think the answer depends in part on what you're trying to do. The
requirements for, say, an ACID-compliant database are much heavier than for
most applications. As far as regular applications go, I'd like to see:

- the above tested and debugged for Windows and MacOS;

- should it save the previous version of the file?

- if so, how many backup files should it keep?

- should it try to sync and flush the disk on saving the file?

- anything I haven't thought of?


Some of those (like the keeping of backups) is probably something that
should be given as an option to the end-user.


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#107630

FromJohn Gordon <gordon@panix.com>
Date2016-04-25 21:26 +0000
Message-ID<nfm22a$qms$1@reader1.panix.com>
In reply to#107620
In <27nshbp40p1llr231dqm31p754tvurkb8i@4ax.com> Seymore4Head <Seymore4Head@Hotmail.invalid> writes:

> On Tue, 19 Apr 2016 18:29:38 -0400, Seymore4Head
> <Seymore4Head@Hotmail.invalid> wrote:

> I am going to forget using a directory path.
> I would like to take the file win.txt and append a space and the *
> symbol.

> f = open('win.txt', 'r+')
> for line in f:
>     f.read(line)
>     f.write(line+" *")

> This doesn't work.  Would someone fix it please?  It is for a task I
> am trying to accomplish just for a home task.

It's much easier to create a new file and then rename it afterwards,
instead of rewriting the original file.

    import os

    f_in = open('win.txt', 'r')
    f_out = open('win_new.txt', 'w')

    for line in f_in.read().splitlines():
        f_out.write(line + " *\n")

    f_in.close()
    f_out.close()

    os.rename('win.txt', 'win_old.txt')
    os.rename('win_new.txt', 'win.txt')

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.python


csiph-web