Title: How to copy single lines into single file for each one
Tags: python;matrix;file-io
Question: I don't know what's wrong with the code it doesn't get me any kind of error message from the shell.
What I'm trying to do is:
Merge all list files from a directory into a single list(with one single column with a single string per row) - done!
Compare that list with a big-file and copy every single correspondent line into a new single file for each line - (maybe?) done! But not working. =/
save the files from step 2 in a new output_directory. - not working.
Remove the correspondent lines from the big-file and save it in the same output_directory - no idea. (maybe pop?)
It's possible to name the output 'singlelinefiles' with the same string used to in step 2? Can anyone show me how?
It would be much appreciated
Here's the code so far:
#!/usr/bin/python
import os, sys, glob
#use: thisone.py <lists_dir&gt;<majorfile&gt;<out_dir&gt;
lists = glob.glob(sys.argv[1]+ '*.txt')
listsmatrix = []
for line in lists:
listsmatrix.append(line.strip().split('\n'))
majorfile = open(sys.argv[2],'r')
majormatrix = []
for line in majorfile:
majormatrix.append(line.strip().split('\t'))
os.mkdir(sys.argv[3])
for line in majormatrix:
if line [0] in listsmatrix:
outfile = open(sys.argv[3]+ 'file'+str(i), 'w')
outfile.write(line)
outfile.close()
i+=1
I'll be thankful for any help from you.


Here is another answer: When you open the file with 'w', the file gets cleared. So every time you open the file, the new line overrides the previous one.
Two possible solutions:
1) Replace 'w' with 'a', so you're appending to the file rather than overwriting it.
2) Open the file once, ideally using a 'with' block so that the file gets closed correctly even if an exception occurs:
with open(sys.argv[3]+ 'file'+str(i), 'w') as outfile:
for line in majormatrix:
if line [0] in listsmatrix:
outfile.write(line)
i+=1
Comment for this answer: thank you man! But it still not working.
Now it creates the output file, but just an empty one outside the output_directory.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:07/05/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><matrix><file-io>', 'Title': 'How to copy single lines into single file for each one', 'ViewCount': 52, 'id': 44917897, 'user_AboutMe': None, 'user_AccountId': 11257794.0, 'user_DisplayName': 'shun', 'user_Reputation': 1.0, 'user_Views': 2.0, 'user_id': 8256959.0}}