简体   繁体   中英

How to read a randomly imported text file and store it in a list

I use file = askopenfile(filetypes=[("Text files","*.txt")]) to let the user choose what text file they'd like to import and I read it with file.read() . I've read on other questions with a similar idea but they only seem to cover what happens when you know the file name. I'd like to know how to read a text file and store the strings in a list in a situation where I don't know what file the user will choose to import. This is what I have so far:

import tkinter
from tkinter.filedialog import askopenfile

file = askopenfile(filetypes=[("Text files","*.txt")])
txt = file.read()
import_list = []

import_list is what I'd like the read file to be stored in.

In order to get the file content, you need to open it for reading (see the Input/Output documentation, section 7.2 for the full options).

In your case, your code could look like this:

import tkinter
from tkinter.filedialog import askopenfile

f = askopenfile(filetypes=[("Text files","*.txt")])

import_list = []

txt = f.read()

import_list.append(txt)
# import_list[-1] now contains txt

# ... any other operations on f.

f.close()

If what you want is import_list to be a list containing all the lines from the file, you can directly use the readlines() function:

import_list = f.readlines()

NB: I changed the variable name in which your store the file name from 'file' to 'file_name', as file is a built-in Type and naming your variable this way was shadowing it (see Documentation, 5.9 ).

txt = file.read() stores the content of the as one String in txt.

If you want to split this string into a list of all lines, you should try the following:

import_list = txt.split('\n')

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