Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Formatting a text file.

$
0
0
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.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>