I have multiple files in multiple directories. All of these files have the same name, and I want to combine those files with the same name as one file, in another directory.
import os
import glob
filenames = [glob.glob(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' ,'Desktop','Test_folder','Input','*.txt')), glob.glob(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop','Test_folder','Output','*.txt'))]
filenames[0].extend(filenames[1])
filenames=filenames[0]
if( not os.path.isdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output'))):
os.mkdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output'))
for fname in filenames:
with open(fname) as file:
for line in file.readlines():
f = open(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output','{:}.txt'.format(os.path.split(fname)[-1] )), 'a+')
f.write(line)
f.close() #This should take care of the permissions issue
But Getting Error:
os.mkdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output'))
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\HOME\\Desktop\\Test_output'
>>>
Edited Code
import os
import glob
filenames = [glob.glob(os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Input/','*.txt')), glob.glob(os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Output/','*.txt'))]
for fname in filenames:
with open(fname).readlines() as all_lines:
for line in all_lines:
f = open(r'C:/Users/Vishnu/Desktop/Test_output/{:}'.format(str(fname.split('/')[-1]), 'a')
f.write('{:}\n'.format(line)
f.close()
Error:
f.write('{:}\n'.format(line)
^
SyntaxError: invalid syntax
C:\\HOMEdoes not exist... Why are you expanding the tilde if you enter the full path?C:\Home\Desktopis what you are going for? Cause in the code you are trying to use directory 'C:\Users\Vishnu\Desktop`C:\Users\Vishnu\Desktop\Test_folder\InputandC:\Users\Vishnu\Desktop\Test_folder\Output. Final output:C:\Users\Vishnu\Desktop\Test_folder\Test_output