Solved

Writing ASCII text files

Posted on 2004-08-19
11
3,728 Views
Last Modified: 2010-04-16
I have a list, to which I have appended various strings, simply using myArray.append("hello") for example. Now I need to write a simple routine that works through the array and saves the contents line by line to a text file (ASCII format).

So.... if I appended "apple", "fish" and "pen" to my array, I'd like the text file to have:

apple
fish
pen

Separated each time by a carriage return, so that when I open it in, say, notepad the entries are on successive lines. The other requirement is that Python creates the file - for some reason my script returns the error that the filename/path of the file does not exist, so I need some kind of command that creates the file in the first place.
0
Comment
Question by:mi5
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 17

Accepted Solution

by:
ramrom earned 60 total points
ID: 11848217
Without knowing the type of myArray we can't answer your question. Please post the script, or enough of it so we know what you are doing.

We could assume myArray is a list, in which case you could convert the list to a string of lines and write the string to the file:

file('c:/foo.txt', 'w').write('\n'.join(myArray))
0
 
LVL 7

Expert Comment

by:BarryTice
ID: 11852980
def ToFile(theList):
    theFile = open('path_and_filename.txt', 'w')
    for thingie in theList:
        theFile.write(thingie + '\n')
    theFile.close

myList = ['apple', 'fish', 'pen']
ToFile(myList)

The above creates the path_and_filename.txt file in your current directory (or wherever you told it to go) with one entry from your list on each line.

-- b.r.t.
0
 
LVL 17

Expert Comment

by:ramrom
ID: 11853064
My solution and BarryTice's are essentially the same, except his:
- is packaged in a function
- has file operations broken out into explicit open, write, close steps
- uses a for loop instead of join
- puts a return after the last line (which the OP did not request)

Please note that Python convention recommends reserving Capitalized names for Class names. Thus you might use toFile instead of ToFile. Also note that the built_in file function is newer (and perferred?) than open.

Please accept one or the other, as they both answer your question.

Bob Gailer
EE Python Page Editor
0
 
LVL 7

Expert Comment

by:BarryTice
ID: 11853150
(I don't mean to step on toes, ramrom. I recognize that your method would work, too. But it is, perhaps, less clear.)
0
 
LVL 17

Expert Comment

by:ramrom
ID: 11853574
And I did not take it as stepping. Just wanting to clarify for the OP. I tend to appreciate terse code, so offer that, and often will expand or clarify later as needed.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 9

Expert Comment

by:rjkimble
ID: 11857326
As long as we're commenting on the relative merits of various approaches, I think that ramrom's approach is crystal clear and more in the spirit of Python. That's my two cents. :-)
0
 
LVL 17

Expert Comment

by:ramrom
ID: 11860031
Aw blush
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11902178
ramrom, quick question, does the file get automatically flushed/closed when the object is garbage collected (I would assume so), also, I've not looked in depth at python GC, but how long will this take to get done in general?
0
 
LVL 17

Expert Comment

by:ramrom
ID: 11904554
f = file('asdf','w')
del f # closes file - no need to wait for GC

This discussion is off topic. To pursue it further please open a new question.

Bob Gailer
EE Python Page Editor
0
 
LVL 17

Expert Comment

by:ramrom
ID: 11904564
mi5: 2nd request:

Please accept one or the other, as they both answer your question.

Bob Gailer
EE Python Page Editor
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11911529
ramrom, not too far off topic, but thanks!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now