Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write strings to another file

Tags:

python

file

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.

like image 472
SSSSSam Avatar asked Sep 20 '26 04:09

SSSSSam


2 Answers

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.

like image 200
zenpoy Avatar answered Sep 23 '26 21:09

zenpoy


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.

like image 38
yurisich Avatar answered Sep 23 '26 21:09

yurisich