Writing out to a directory in python

  • Python
  • Thread starter dacruick
  • Start date
  • #1
1,033
1
Hi, I have a program which is reading in line by line information, saving that, and writing it out to a file. How do I change where the files are created? Also, can I create a folder to write the files out to in my program?

The second issue I have is this. right now my program opens the file, reads a line, writes a line, reads a line, writes a line, until its finished. I want it to read all of the lines, then open the file, then write all of them. Would I save all my lines to an array then fout.write(array[0:x],'w')??
 
Last edited:

Answers and Replies

  • #2
418
3
os.chdir(path) changes the dir. readlines() will read all the lines in a file.
 
  • #3
673
2
Also, can I create a folder to write the files out to in my program?
os.mkdir(newdir)

Would I save all my lines to an array then fout.write(array[0:x],'w')??
Think like a python person: lists, dude, lists.
You can do the readlines in a list iteration:
newtxt = open(newtext, 'w')
words = [readlines(file) for file in file_list]
text = " ".join(words)
newtxt.write(text)
 
Last edited:
  • #4
1,033
1
I had the list and it wasnt working. But i figured it out. apparantly the newtxt.write function will not work for multiple lines. I had a list of lines from 0 - x and i was trying to use newtxt.write(list[0:x]) and it was giving me some stupid out of range errors. But I got it and if you wanted to know its the newtxt.writelines function. but thanks
 
  • #5
673
2
But I got it and if you wanted to know its the newtxt.writelines function. but thanks
Thanks. The whole point of using the join is to get around the weird list things. You effectively turn the text into one long string that you're writing out. A "\n".join(text) may work for creating new lines.
 
  • #6
1,033
1
yeah the endline wasnt an issue here. It seems that the line that i read out of a file included some form of endline so that when i saved them to my list it saved the endline too
 

Related Threads on Writing out to a directory in python

Replies
2
Views
25K
Replies
9
Views
16K
Replies
4
Views
1K
Replies
15
Views
824
Replies
11
Views
3K
  • Last Post
Replies
20
Views
3K
Replies
9
Views
1K
Top