首页 > 解决方案 > How to write a list in a separate text file in python?

问题描述

I am trying to parse some data from multiple text files that I have in directory of my computer.

I want to copy specific information from each of the file to a separate text file. I am making some mistake, but don't understand what. Please see the code below. I'd really appreciate your help.

texts = []
for file in OK_files:
    with open(path + '\\' + file) as f:
        # this t varialble store your 2nd line in each cycle
        t = f.read().split('\n') [1]
        # this file append each file into texts list
        texts.append(t)

# to print each important line

with open("C:/Users/rafi.nazmul/Documents/Output","w+") as file:
    for text in texts:
        file.write(texts)

I was getting error:

TypeError: write() argument must be str, not list

Update

The error is fixed from the comments, but I need to know couple more things:

  1. The code now reads only one line, 1st indexed, from each file. How can I read multiple lines from each of the files?
  2. How can I select particular characters from each of the line instead of the whole line?

标签: pythonlistparsingtext-fileswriting

解决方案


In the write() function, you're passing the whole list of lexts. Just change it to:

for text in texts:
    with open(file_path,'a') as file:
        file.write(text)

We're using 'a' because we want to open the file and append to it, not overwrite it. Also, please check whether you have anything in the texts. Note that, the file_path includes the file_name with extension too.


推荐阅读