473,379 Members | 1,243 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

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.txt")
w = open("newfile.txt", "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 8330
"Alex Nordhus" <me******@gte.net> 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.txt")
w = open("newfile.txt", "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.org> 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.net> 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.txt")
w = open("newfile.txt", "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.txt', 'w')
for line in f.split('\n'): .... w.write(line)
.... w.close()
'\n' in open('/home/wandleg/outfile.txt').read()

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.txt")
w = open("newfile.txt", "w")
for line in f:
if line.strip():

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

g = open("newfile.txt")
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.net> 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.org> 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
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,...
3
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...
29
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
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 -...
5
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...
11
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...
3
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 -...
1
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
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
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.