2 Replies - 291 Views - Last Post: 26 January 2013 - 03:58 PM Rate Topic: -----

#1 Worshy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-January 13

Formatting a text file.

Posted 26 January 2013 - 03:45 PM

Hey! I'm jsut learning Python (I just finished the codecademy course) and am working on this project. I have a text file which is pretty much just numbers that I want to re-format (ie. change the layout). My problem is that I'm not too sure how to get each number in turn since they are different lengths and have varying (1-3) spaces between them so I can't just use string slicing since the numbers are always in different positions. I was hoping someone could help me with this.

Here's the crux of my code so far: (I'm sure you'll find more errors, I apoligise since this is my first project)
oldfile = open("old.txt","r")
newfile = open("new.txt","w")

date = "00/00/00"
for line in oldfile:
  id = #first number
  numbers = #string of following numbers
  newfile.write(str(date, id + ":", numbers)

newfile.close()
oldfile.close()



Here's an example of the raw data:
810 21 35 68 414 19 3 37 42 13 37 48 23 155 6 9 647 38 173 74 78

Here's an example of what I want the final product to be:
10-12-2012 810: 21 35 68 414 19 3 37 42 13 37 48 23 155 6 9 647 38 173 74 78

My current problem is iterating over the raw data and separating the numbers from whitespaces and the first number from the rest. I would greatly appreciate any help on this project. Thanks in advance.

Well my example didn't come out as it should have. Sorry but I can't find how to edit the post, however, between the numbers in the raw data are varying number of spaces (the post shows that each one has a single space between it). The spaces between them vary from 1-3.

Is This A Good Question/Topic? 0
  • +

Replies To: Formatting a text file.

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,204
  • Joined: 21-June 11

Re: Formatting a text file.

Posted 26 January 2013 - 03:53 PM

You can use the split method to split the line into words separated by arbitrary amounts of spaces. You can then simply index into the list to get the id and use list slicing to get the numbers without the id. You can then use the join method to concatenate the numbers back into a single string separated by a single space.

This post has been edited by sepp2k: 26 January 2013 - 03:54 PM

Was This Post Helpful? 1
  • +
  • -

#3 Worshy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-January 13

Re: Formatting a text file.

Posted 26 January 2013 - 03:58 PM

Thanks, I'll google the split method and give your method a shot now.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1