简体   繁体   中英

I have a list with a set of questions. I want each of these questions to go into separate .txt files. How do I do that?

This is my list. I want each element in a different.txt file

['What is Income tax?',
 'What is the period for which a person’s income is taken into account for the purpose of Income tax?',
 'What is Indirect Tax?',
 'What is the Goods and Service Tax (GST)?',
 'What is a composition scheme?',
 'Who can opt for a composition scheme?',
 'I have some queries regarding taxation of my business, can anyone help?',
 'Direct tax and indirect tax.',
 'How are small businesses taxed in India?',
 'information related to tax',
 'how do i calculate tax as per new rules']

Assuming you are hardcoding the statements as a list in the script you are trying to write in python, you can do something like this:

# Hard-coded statements
statements = ['statement1', 'statement2', ...] 

# Loop through all the statements
for index, statement in enumerate(statements):

    # Create a new text file with the index as the filename
    with open('{}.txt'.format(index), 'w') as output_file:

        # Write the statement into the text file
        output_file.write(statement)

This automatically uses the index as the filename. You can also specify the filenames if you store it in a separate list like so:

# Hard-coded statements
statements = ['statement1', 'statement2', ...] 

# Hard-coded filenames
filenames = ['statement1.txt', 'statement2.txt', ...]

# Loop through all the statements
for index, statement in enumerate(statements):

    # Create a new text file with the index as the filename
    with open(filenames[index], 'w') as output_file:

        # Write the statement into the text file
        output_file.write(statement)

You can probably imagine there are a number of different ways to go about this particular problem, but hopefully this gives you a starting point.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM