3

The Problem - Update:

I could get the script to print out but had a hard time trying to figure out a way to put the stdout into a file instead of on a screen. the below script worked on printing results to the screen. I posted the solution right after this code, scroll to the [ solution ] at the bottom.

First post:

I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (:) and write them into another txt file. So far I am able to print the results on the screen and it works perfectly, but when I try to write the results to a new file it gives me str has no attribute write/writeline. Here it the code snippet:

# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess

x = raw_input("Enter the full path + file name + file extension you wish to use: ")
def ripple(x):
  with open(x) as file:
    for line in file:
      for word in line.split():
        if ':' in word:
          try:
            print word.split(':')[-1]
          except (IndexError):
            pass 

ripple(x) 

The code above works perfectly when printing to the screen. However I have spent hours reading Python's documentation and can't seem to find a way to have the results written to a file. I know how to open a file and write to it with writeline, readline, etc, but it doesn't seem to work with strings.

Any suggestions on how to achieve this?

PS: I didn't add the code that caused the write error, because I figured this would be easier to look at.

End of First Post

The Solution - Update:

Managed to get python to extract and save it into another file with the code below.

The Code:

inputFile = open ('c:/folder/Thefile.txt', 'r')
outputFile = open ('c:/folder/ExtractedFile.txt', 'w')
tempStore = outputFile
for line in inputFile:
    for word in line.split():
        if ':' in word:
            splitting = word.split(':')[-1]
            tempStore.writelines(splitting +'\n')
            print splitting

inputFile.close()
outputFile.close()

Update:

checkout droogans code over mine, it was more efficient.

Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
SSSSSam
  • 113
  • 1
  • 2
  • 8
  • 4
    "cause i figured this would be easier to look at." - but how can we solve the problem then? – Simeon Visser Jul 15 '12 at 10:06
  • The last word: `[l for l in open('data.txt')][-1].split(':')[-1].strip()`. – Vidul Jul 15 '12 at 12:13
  • @SimeonVisser: your right i was just hoping my explanation would give a hint i figured if i posted what i was trying to achive it would throw everybody off as i am new to this. but for sure from now on i will always add the rest of the code. Thank you though for your comment. – SSSSSam Jul 15 '12 at 17:03
  • @BNAYN sorry i dont have the same keyboard couldnt type your name right. I tried what you suggested but it only took the last line from the list. maybe its me im very new to this but thank you for your help – SSSSSam Jul 15 '12 at 17:05

3 Answers3

3

Try this:

with open('workfile', 'w') as f:
    f.write(word.split(':')[-1] + '\n')

If you really want to use the print method, you can:

from __future__ import print_function
print("hi there", file=f)

according to Correct way to write line to file in Python. You should add the __future__ import if you are using python 2, if you are using python 3 it's already there.

Community
  • 1
  • 1
zenpoy
  • 19,490
  • 9
  • 60
  • 87
  • Thanks for pointing out the additional functionality of the `print` function. Good to know. – yurisich Jul 15 '12 at 16:36
  • @zenpoy: Thank you very much, I tried what you suggested but i struggled i guess cause im very new to python and coding/scripting. Thank you again. – SSSSSam Jul 15 '12 at 17:01
1

You are trying to call .write() on a string object.

You either got your arguments mixed up (you'll need to call fileobject.write(yourdata), not yourdata.write(fileobject)) or you accidentally re-used the same variable for both your open destination file object and storing a string.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

I think your question is good, and when you're done, you should head over to code review and get your code looked at for other things I've noticed:

# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess

First off, thanks for putting example file contents at the top of your question.

x = raw_input("Enter the full path + file name + file extension you wish to use: ")

I don't think this part is neccessary. You can just create a better parameter for ripple than x. I think file_loc is a pretty standard one.

def ripple(x):
  with open(x) as file:

With open, you are able to mark the operation happening to the file. I also like to name my file object according to its job. In other words, with open(file_loc, 'r') as r: reminds me that r.foo is going to be my file that is being read from.

    for line in file:
      for word in line.split():
        if ':' in word:

First off, your for word in line.split() statement does nothing but put the "Hello:there:buddy" string into a list: ["Hello:there:buddy"]. A better idea would be to pass split an argument, which does more or less what you're trying to do here. For example, "Hello:there:buddy".split(":") would output ['Hello', 'there', 'buddy'], making your search for colons an accomplished task.

          try:
            print word.split(':')[-1]
          except (IndexError):
            pass 

Another advantage is that you won't need to check for an IndexError, since you'll have, at least, an empty string, which when split, comes back as an empty string. In other words, it'll write nothing for that line.

ripple(x) 

For ripple(x), you would instead call ripple('/home/user/sometext.txt').

So, try looking over this, and explore code review. There's a guy named Winston who does really awesome work with Python and self-described newbies. I always pick up new tricks from that guy.

Here is my take on it, re-written out:

import os #for renaming the output file

def ripple(file_loc='/typical/location/while/developing.txt'):
    outfile = "output.".join(os.path.basename(file_loc).split('.'))

    with open(outfile, 'w') as w:
        lines = open(file_loc, 'r').readlines() #everything is one giant list
        w.write('\n'.join([line.split(':')[-1] for line in lines]))

ripple()

Try breaking this down, line by line, and changing things around. It's pretty condensed, but once you pick up comprehensions and using lists, it'll be more natural to read code this way.

Community
  • 1
  • 1
yurisich
  • 6,991
  • 7
  • 42
  • 63
  • I read your suggestions and it makes more sense your way, my code above is my first script but thanks to you for explaining in depth i will improve at this and i am sure a lot of others that find this will benefit also. god bless you. p.s i am using your code over mine :D – SSSSSam Jul 16 '12 at 10:12
  • No problem, you figured out your problem but came here for better ways to do things. You'll learn much faster if you use SO/CR that way. – yurisich Jul 16 '12 at 13:37