I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is there a way to do this as the current output is almost unreadable?
-
You just need to explicitly append a
'\n'each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use os.linesep instead, if you had to output in binary mode for some reason, but that's a pretty unusual use case -- normally, text mode and\nare much better).Dynamo : This worked perfectly. Sorry if this seemed easy but as I stated this is my first time trying to do something like this.Alex Martelli : @Dynamo, sure, we've all been beginners at some point!-)e-satis : Well, I'm not supposed to be a Python beginer, and discover os.linesep with your answer.From Alex Martelli -
I am wondering why you don't have a line break when you print. an example.
>>> import os >>> for files in os.listdir("."): ... if os.path.isfile(files): ... print "file: ",files," length: ",len(files) ... file: test1 length: 5 file: shell.sh length: 8 file: test.txt length: 8Dynamo : There is a line break when I use the print command in the console but when I write to the text file it was not showing up. That's part of the reason I was confused as the console did not require me to use \n to create the line break.ghostdog74 : yes, if you are using write() method, you need to append "\n"From ghostdog74
0 comments:
Post a Comment