Note that there are some explanatory texts on larger screens.

plurals
  1. POWrite strings to another file
    primarykey
    data
    text
    <p><strong>The Problem - Update:</strong></p> <p>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.</p> <p><strong>First post:</strong></p> <p>I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (<code>:</code>) 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 <code>str has no attribute write/writeline</code>. Here it the code snippet:</p> <pre><code># 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) </code></pre> <p>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.</p> <p>Any suggestions on how to achieve this?</p> <p>PS: I didn't add the code that caused the write error, because I figured this would be easier to look at. </p> <p><strong>End of First Post</strong></p> <p><strong>The Solution - Update:</strong></p> <p>Managed to get python to extract and save it into another file with the code below.</p> <p><strong>The Code:</strong></p> <pre><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() </code></pre> <p><strong>Update:</strong></p> <p>checkout droogans code over mine, it was more efficient.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload