Is it possible if i have several columns to have my output go to. If I want to use column 3 as the storage location of my output files. main_folder below contains folder1,folder2, folder3
C:/Desktop/main_folder/
file.txt
Bob November folder_1
Jon January folder_3
Sam December folder_1
Jane April folder_2
path = /Desktop/main_folder/*
with open('file.txt', 'r') as input:
for lines in input:
line = line.strip()
with open(output, 'w') as outfile:
outfile.write(line, path)
Is it possible to select just column 3 and use that path as output?
CodePudding user response:
Try this
with open('file.txt', 'r') as input:
for line in input:
columns = line.strip().split() # split line into columns using spaces as delimiter
path = os.path.join('/Desktop/main_folder', columns[2]) # path is built from main-folder and third column
with open(path, 'w') as outfile:
outfile.write(line) # write the line to it's respective file path
Step by step explanation
- This code reads each line of the input file
- Then splits it into columns using the
split()
method. - It takes the third column (index 2) and combines it with the base path
/Desktop/main_folder
usingos.path.join()
to create the full output path. - Finally, it opens the output file at the specified path and writes the original line to it.
Note: this code assumes that the input file is in the format you provided, with the columns separated by spaces. If the columns are separated by a different character, you will need to use a different method to split the line into columns.
See also: python 3.x - Create new folder with pathlib and write files into it