将文件夹中的多个文本文件加载到python列表变量中

时间:2017-02-23 05:43:58

标签: python

我有一个充满文本文件的文件夹。我想使用python将所有这些文本文档加载到单个列表变量中。列表变量应将每个文本文档作为项目。

到目前为止,我有这个代码,但它不能正常工作。

$user_save_obj = User::Create([
    'user_email' => $data['user_email'],
    'user_password' => bcrypt($data['user_password']),
    'first_name' => 'John',
    'last_name' => 'Doe',
    'department_id' => 1,
    'user_level' => 1,
    'create_date' => Carbon::now('Asia/Jakarta')
])

$last_inserted_id = $user_save_obj->id;

$user_update_obj = User::find($last_inserted_id);
$user_update_obj->created_by = $last_inserted_id;
$user_update_obj->save();

有更好的方法吗?

编辑:用文本阅读功能(readlines())替换了csv阅读功能(read_csv)。

4 个答案:

答案 0 :(得分:1)

您只需要read()每个文件,并将其附加到corpus列表,如下所示:

import glob
import os

file_list = glob.glob(os.path.join(os.getcwd(), "FolderName", "*.txt"))

corpus = []

for file_path in file_list:
    with open(file_path) as f_input:
        corpus.append(f_input.read())

print corpus  

每个列表条目将是每个文本文件的全部内容。请注意,使用readlines()会为您提供每个文件的行列表,而不是原始文本。

答案 1 :(得分:1)

  • 使用 pathlib 模块
  • 使用Path()创建路径的pathlib对象(或使用.cwd()),并使用.glob(或.rglob())查找文件匹配特定模式。
    • files = (Path().cwd() / 'FolderName').glob('*.txt')
      • / 用于向 pathlib 对象添加文件夹(扩展)。
    • 替代方案:
      • files = Path('./FolderName').glob('*.txt')
      • files = Path('e:/PythonProjects/stack_overflow/t-files/').glob('*.txt')
  • Path.read_text() 可用于将文本读入 list,而无需使用 .open()
    • text = [f.read_text() for f in files]
    • 替代方案:
      • text = [f.open().read() for f in files]
      • text = [f.open().readlines() for f in files] - 创建 listlists 文本。
from pathlib import Path

# get the files
files = (Path().cwd() / 'FolderName').glob('*.txt')

# write the text from each file into a list with a list comprehension
text = [f.read_text() for f in files]

for-loop 替代方案

选项 1

files = Path('./FolderName').glob('*.txt')

text = list()

for file in files:
    text.append(file.read_text())

选项 2

  • Path.open().read() 可用于打开文件文本并将其读入列表。
files = Path('./FolderName').glob('*.txt')

text = list()

for file in files:
    with file.open() as f:
        text.append(f.read())

答案 2 :(得分:0)

我发现这是一种更简单的方法:

    import glob


    corpus = []

    file_list = glob.glob("Foldername/*.txt")
    for file_path in file_list:
        with open(file_path, 'r') as file_input:
           corpus.append(file_input.read())
    print (corpus)

答案 3 :(得分:-1)

import os
import shutil
import csv
import sys

csv_file = "card.csv"

with open(csv_file, 'r') as f:
    reader = csv.reader(f)
    for i, row in enumerate(reader):
        if i == 0:
            print(i)
            pass    # Skip header row
        else:
            filename,filepath,x,y,w,h = row

            file2 = filename + ".txt"    
            file1 = open(file2,"a")#append mode 
            file1.write("%s\n%s\n%s\n%s\n" % (x, y, w,h)) 
            file1.close() 
相关问题