472,952 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Delete spaces

If I have a text file that is delimited by spaces, how do I import it
and get to comma delimited? Here is a row of data from the text file:

1 1 10:55:14 2 65 8.5
1.4+1.1 2.5 Class-2 0

I tried a few examples from the group and it didn't work, since the
file also has a header row and a row of seperators ( -------). The
lengths of each row is something like 130, so there are extra spaces
after the last value as well. I have tried joining and other things,
but I couldn't figure out how to get the values to come together.
Thanks.

Kou

Sep 28 '07 #1
4 2945
ko****@hotmail.com a écrit :
If I have a text file that is delimited by spaces,
spaces or tabs ?
how do I import it
and get to comma delimited? Here is a row of data from the text file:

1 1 10:55:14 2 65 8.5
1.4+1.1 2.5 Class-2 0
I tried a few examples from the group and it didn't work, since the
file also has a header row and a row of seperators ( -------). The
lengths of each row is something like 130, so there are extra spaces
after the last value as well. I have tried joining and other things,
but I couldn't figure out how to get the values to come together.
Thanks.
This should answer your question - but certainly not solve your problem
(cf below):

f = open('/path/to/file.txt');
file.readline(); # skip headers
for line in f:
# skip separators
if line.startswith('---'):
continue
parts = filter(line.rstrip().split())
print ';'.join(parts)

f.close()
Now the problem is that, obviously, the position of a group of data in a
line is meaningfull, so just filtering out spaces isn't the solution.
Did you check that it's not really a tab-delimited file ? If yes, doing
line.split('\t') might help. Or just trying with the csv module FWIW.

My 2 cents...
Sep 28 '07 #2
ko****@hotmail.com wrote:
If I have a text file that is delimited by spaces, how do I import it
and get to comma delimited? Here is a row of data from the text file:

1 1 10:55:14 2 65 8.5
1.4+1.1 2.5 Class-2 0

I tried a few examples from the group and it didn't work, since the
file also has a header row and a row of seperators ( -------). The
lengths of each row is something like 130, so there are extra spaces
after the last value as well. I have tried joining and other things,
but I couldn't figure out how to get the values to come together.
Thanks.

Kou

After you recognize and handle the header and separator lines, the
remaining lines can be handled this way:
>>l = '1 1 10:55:14 2 65 8.5'
f = l.split()
print f
['1', '1', '10:55:14', '2', '65', '8.5']
>>','.join(f)
'1,1,10:55:14,2,65,8.5'

or
>>', '.join(f)
'1, 1, 10:55:14, 2, 65, 8.5'
>>>
Gary Herron
Sep 28 '07 #3
On Sep 29, 1:43 am, kou...@hotmail.com wrote:
If I have a text file that is delimited by spaces, how do I import it
and get to comma delimited? Here is a row of data from the text file:

1 1 10:55:14 2 65 8.5
1.4+1.1 2.5 Class-2 0

I tried a few examples from the group and it didn't work, since the
file also has a header row and a row of seperators ( -------). The
lengths of each row is something like 130, so there are extra spaces
after the last value as well. I have tried joining and other things,
but I couldn't figure out how to get the values to come together.
Thanks.

Kou
It would help enormously if you could show us UNAMBIGUOUSLY what is in
say the first 3 lines after the headings and separators -- do this:

print repr(open("thefile", "rb").read()[:400])

The other thing you need is to know enough about the file format to
show us what is the CSV output that you require from the sample input
-- we don't have crystal balls, and are likely to make half-donkeyed
guesses, like these:

If the spaces are really tabs, use line.split('\t')

Otherwise: the file has fixed column widths, and any use of line.split
will mangle it.

The clumsy way to handle this is to count column positions, and write
something ugly like:
field1 = line[0:8]
field2 = line[8:20]
etc

"a row of seperators ( -------)" sounds suspiciously like the "column
aligned" format that can be produced by running a SQL query on a SQL
Server database using MS's "Query Analyser". It looks like this:

RecordType ID1 ID2 Description
----------- -------------------- ----------- ----------------------
1 12345678 123456 Widget
4 87654321 654321 Gizmoid
etc

Does your file look something like that? If so, then all you have to
do is leverage off the fact that the second line has one-space gaps
between each bunch of dashes, and you can write a little module that
will read any file like that, just as though it were a CSV file.

Over to you ....

Cheers,
John

Sep 29 '07 #4

John Machin wrote:
On Sep 29, 1:43 am, kou...@hotmail.com wrote:
If I have a text file that is delimited by spaces, how do I import it
and get to comma delimited? Here is a row of data from the text file:

1 1 10:55:14 2 65 8.5
1.4+1.1 2.5 Class-2 0

I tried a few examples from the group and it didn't work, since the
file also has a header row and a row of seperators ( -------). The
lengths of each row is something like 130, so there are extra spaces
after the last value as well. I have tried joining and other things,
but I couldn't figure out how to get the values to come together.
Thanks.

Kou

It would help enormously if you could show us UNAMBIGUOUSLY what is in
say the first 3 lines after the headings and separators -- do this:

print repr(open("thefile", "rb").read()[:400])

The other thing you need is to know enough about the file format to
show us what is the CSV output that you require from the sample input
-- we don't have crystal balls, and are likely to make half-donkeyed
guesses, like these:

If the spaces are really tabs, use line.split('\t')

Otherwise: the file has fixed column widths, and any use of line.split
will mangle it.

The clumsy way to handle this is to count column positions, and write
something ugly like:
field1 = line[0:8]
field2 = line[8:20]
etc

"a row of seperators ( -------)" sounds suspiciously like the "column
aligned" format that can be produced by running a SQL query on a SQL
Server database using MS's "Query Analyser". It looks like this:

RecordType ID1 ID2 Description
----------- -------------------- ----------- ----------------------
1 12345678 123456 Widget
4 87654321 654321 Gizmoid
etc

Does your file look something like that? If so, then all you have to
do is leverage off the fact that the second line has one-space gaps
between each bunch of dashes, and you can write a little module that
will read any file like that, just as though it were a CSV file.
If the fields are separated by whitespace, this Awk program can
handle the situation:

awk 'BEGIN{OFS=","} {$1=$1} 1' oldfile >newfile

If the fields are fixed-width and the 2nd line is a guide to those
widths,
then this Ruby program should work (not optimized for speed):

lines = IO.readlines( 'data2' )
# Dump header.
lines.shift
# Save column guide.
guide = lines.shift.scan( /-+ */ )
for line in lines do
puts guide.map{|s| line.slice!(0,s.size).strip}.join(",")
end

Sep 30 '07 #5

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

Similar topics

7
by: Mindy Geac | last post by:
Is it possible to delete special caracters from a string and multiple spaces? When the input is : "a&*bbb cc/c d!d" I want the result : "abbb ccc dd" thnx. MJ <?php
2
by: jim Bob | last post by:
Hi, I have a form with a list box that shows the contents of a table and managed to create an add record button with the wizard. (DoCmd.GoToRecord , , acNewRec) Now i want to make a delete...
10
by: felixnielsen | last post by:
Hi, im pretty new to this so plz cut me some slag ;-) anyhow, i need to delete an array, or what i really need is to increase the array size, i was think i could be done by copying the array into...
5
by: wo20051223 | last post by:
Deleting some files with C# fails with "Access to the path 'X' is denied". I have files copied from a CD that I burned (and not locked by a process) and a text file that I created in Windows...
7
by: ClarkePeters | last post by:
I have large text files that I read into an array, but before that I take out all the special characters such as tabs, new lines, and returns. However I'm left with all the extra spaces (sometimes...
10
by: amiga500 | last post by:
Hello, I have one basic simple question. When I have multiple records in the datagrid as follows: Code Product 1 Product 2 Product 3 11111 A B C...
4
by: - HAL9000 | last post by:
When un-installing an application... Is it normal practice to write a special program that erases all the files and folders for all the users of an application that reads and writes to...
3
by: rudeman76 | last post by:
Hello, I have 2 DB that are linked (they are pretty much identical). I have an append sql statement. It works fine for most of it. I just have two questions. 1. When I started the DB I was...
4
codemama
by: codemama | last post by:
I have created xml files in C# using the DataSet ds.WriteXml method. I now need to take an xml file and be able to do an insert or delete to a table in MS Access. How would I go about that? Do...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.