How to divide a text file that have multiple string to many text files. Like this
inside textfile.txt string 1 string 2 string 3 string 4 string n+1
then divide to multiple textfile and name the txt file to the string inside textfile.txt
string 1.txt string 2.txt string 3.txt string 4.txt
and so on until the the loop of the string stop until n+1
import csv
with open('inputTextFile.txt', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
for fileName in reader:
open(fileName, 'a').close()
'a' ensures that if the file already exists and it has some content then it is not overwritten. This may or may not work depending on the format of your inputTextFile. This is assuming that the strings are delimited by spaces. You can read about csv here: https://docs.python.org/3/library/csv.html
Something like this will write each line of the input file to a separate output file (if that's what you meant):
with open('textfile.txt', 'rt') as inf:
for linenum, line in enumerate(inf, start=1):
filename = 'string {}.txt'.format(linenum)
with open(filename, 'wt') as outf:
outf.write(line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.