Solved

Writing ASCII text files

Posted on 2004-08-19
11
3,729 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
converting return from type() function in python to string 1 72
Getting python error while running ansible command 2 105
python question 5 69
What is Python programming? 3 103
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

920 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

17 Experts available now in Live!

Get 1:1 Help Now