473,555 Members | 2,336 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Newline at EOF Removal



I am looking for a way to strip the blank line and the empty newline at
the end of the text file. I can get the blank lines removed from the
file but it always leaves the end line (which is blank) as a newline. My
code is here and it works but leaves the newline at the end of the file.
How do I get rid of it?

import re
f = open("oldfile.t xt")
w = open("newfile.t xt", "wt")
for line in f.readlines():
line = re.sub(r'^\s+$' , '', line)
w.write(line)

w.close()

I have tried everything I know and still falling short. Any help?

Jan 9 '06 #1
7 8349
"Alex Nordhus" <me******@gte.n et> writes:
I am looking for a way to strip the blank line and the empty newline at
the end of the text file. I can get the blank lines removed from the
file but it always leaves the end line (which is blank) as a newline. My
code is here and it works but leaves the newline at the end of the file.
This really isn't a very clear description of the problem. Does your
file end with two newlines in row? That would be what you'd get if it
ended with the newline for the last line. If it ends with just one
newline, then you're not getting the a blank last line, you're simply
getting a last line that ends with a newline.
How do I get rid of it?

import re
f = open("oldfile.t xt")
w = open("newfile.t xt", "wt")
for line in f.readlines():
line = re.sub(r'^\s+$' , '', line)
w.write(line)


This is an abuse of regular expressions (see
http://www.mired.org/home/mwm/spare/ ); simple string methods can do
this job for you. Try:

for line in f:
if line.strip():
w.write(line)

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jan 9 '06 #2
On Sun, 08 Jan 2006 17:10:01 -0600, "Alex Nordhus" <me******@gte.n et> wrote:


I am looking for a way to strip the blank line and the empty newline at
the end of the text file. I can get the blank lines removed from the
file but it always leaves the end line (which is blank) as a newline. My
code is here and it works but leaves the newline at the end of the file.
How do I get rid of it?

import re
f = open("oldfile.t xt")
w = open("newfile.t xt", "wt")
for line in f.readlines():
line = re.sub(r'^\s+$' , '', line)
w.write(line)

w.close()

I have tried everything I know and still falling short. Any help?


First, you don't need re for that, and second, why write a zero-length ''?
It might even confuse some file system. You don't need readlines either. Try
(untested)
# open f and w as before [1]
for line in f:
if line.strip(): w.write(line) # write only non-blank lines

[1] BTW, I didn't see the 't' mode in http://docs.python.org/lib/built-in-funcs.html
description of open/file, but I have a nagging doubt about saying it's not valid.
Where did you see it?

Regards,
Bengt Richter
Jan 9 '06 #3
Do you mean somthing like this?
f = open("file.txt" )
w = open('outfile.t xt', 'w')
for line in f.split('\n'): .... w.write(line)
.... w.close()
'\n' in open('/home/wandleg/outfile.txt').r ead()

False

Jan 9 '06 #4
Thank you guys for all your help. Was able to nail it down.
uh I dunno where i saw the 'wt' at. somewhere online though.
I have to do it in 2 stages though and run through a coula files but it
works.
import re
f = open("oldfile.t xt")
w = open("newfile.t xt", "w")
for line in f:
if line.strip():

w.write(line)
f.close()
w.close()

g = open("newfile.t xt")
x = open("mynewfile .txt", "w")

x.write(g.read( ).rstrip('\n'))

x.close()

Got around the I/O errors luckily
thanks guys

Jan 9 '06 #5
Actually Im doing a process with PHP, Unicode, Ansi. I am trying to
format these text files to be acceptable to PHP. The first process is
to strip the unicode and convert to ansi. But there are blank lines in
the file and at the end of the file. I was just having trouble with the
lines at the end. PHP blows up if there is a blank or empty line in the
text files. So thats where i was at.
Peter gave me a good clue here
w.write(f.read( ).rstrip('\n') + '\n')
However the 2nd \n puts that empty line at the end of the file so I
tried it with just
w.write(f.read( ).rstrip('\n'))
and it works great!

Now I can go on to the next step. Thank you guys for your help

Alex

Jan 9 '06 #6
[Bengt Richter]
...
[1] BTW, I didn't see the 't' mode in http://docs.python.org/lib/built-in-funcs.html
description of open/file, but I have a nagging doubt about saying it's not valid.
Where did you see it?


't' is a Windows-specific extension to standard C's file modes.
Python passes mode strings as-is on to the platform C library, so if
your platform C likes 't', you're free to use it.

You might think there's no point to passing 't', since text mode is
the default. If so, you'd almost be right ;-). The rub is that
Windows also supports another non-standard gimmick, to make binary
mode the global default instead (although very few know about this,
and I've never seen it used in real life). If you've done that, then
't' is necessary to get text mode.
Jan 9 '06 #7
"Alex N" <me******@gte.n et> writes:
Peter gave me a good clue here
w.write(f.read( ).rstrip('\n') + '\n')
However the 2nd \n puts that empty line at the end of the file so I
No, it doesn't. Well, maybe it doesn't, depending on how your
applications treats newlines. Normally, a newline terminates a line,
so a file ending in "...some-alpha-text\n" ends in a complete
line. Python agrees with this, as file.readlines won't return a list
with a final empty string in it if fed a file whose last character is
a newline.
tried it with just
w.write(f.read( ).rstrip('\n'))
and it works great!


This one ends in "...some-alpha-text". I'd say it ended in an
"incomplete " line, because the last line doesn't have a trailing
newline. My editor would agree - it warns me if I try and save a file
with an incomplete final line.

From what you've said, PHP apparently treats newlines as line
*separators*, not terminators. So a file that ends in a final newline
ends with a final blank line.

I suspect that part of your problem is trying to deal with the two
different views of what a newline does.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jan 9 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
9004
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if...
3
6597
by: sanjana | last post by:
hi willy i have done the code for detecting insertion/removal of device at USB port thanx for ur advice but is there way to detect if sd card is inserted or removed from the device at usb tht is i want to check for sd card insert/remove events thanx
29
3422
by: runningdog | last post by:
Hi, I would like to be able to embed a newline in a text string. Is there any convienent notation to do this TIA Steve
4
4463
by: Peter Kirk | last post by:
Hi I would like to ask a little bit about the value Environment.Newline: what is it and what is the point of it? Ok, I can see in the docs that it represents "newline" for the current platform - I assume that it is a runtime property, and not compile time? But won't it always be the same anyway - does dotnet run on anything other than...
5
6980
by: Adam Right | last post by:
Hi, Is there a way to construct the mail body including newline characters by using .net framework mailing functions when sending an email? I cannot insert newline character into the body of the mail. Thanks...
11
6216
by: rossum | last post by:
I want to declare a const multi-line string inside a method, and I am having some problems using Environment.NewLine. I started out with: class foo { public void PrintStuff() { const string multiline = "The first line." + Environment.NewLine +
3
2046
by: tschwartz | last post by:
I'm trying to write a stylesheet which removes nodes which are empty as a result of other template processing. For example, given the following xml, I'd like to: - remove all "b" elements - remove all "a" elements which, as a result of "b" element removal, now have no children so, starting with:
1
8492
by: linq936 | last post by:
Hi, I read in many places that the string to be outputted by printf() must be ending with newline, for example, it should be printf("Hello World.\n"); instead of printf("Hello World.");
1
1366
by: irfan200x | last post by:
Does Any Body Have The Key and User name of Adware removal 8.0.1 Please give me the key and user or some one have a Adware Removal 8.0.1 Full Software then send to me to this id thak you bye
0
7547
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8060
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7588
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5452
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5171
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3596
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
865
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.