Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonでフォルダから複数のテキストファイルを読み取る方法は?(Tkinter)


Pythonは、ファイル、オブジェクトを処理し、さまざまなアプリケーションを作成することができます。 Pythonの拡張機能とパッケージを使用して、フル機能のアプリケーションを構築および開発できます。

システム内のファイルを制御したいとします。次に、Pythonは、オペレーティングシステム内のファイルと対話できるようにするシステム対応機能を備えたOSモジュールを提供します。

PythonのOSモジュールを使用して、フォルダから複数のテキストファイルを読み取る方法を見てみましょう。

  • ノートブックにOSモジュールをインポートします。

  • システム内でテキストファイルが配置されるパスを定義します。

  • ファイルのリストを作成し、繰り返して、すべてのファイルの拡張子が正しいかどうかを確認します。

  • モジュールで定義された関数を使用してファイルを読み取ります。

# Import the required libraries
import os

# Define the location of the directory
path =r"C:/Users/Sairam/Documents/"

# Change the directory
os.chdir(path)

def read_files(file_path):
   with open(file_path, 'r') as file:
      print(file.read())

# Iterate over all the files in the directory
for file in os.listdir():
   if file.endswith('.txt'):
      # Create the filepath of particular file
      file_path =f"{path}/{file}"

read_files(file_path)

出力

Sample 1
========
Welcome to Tutorialspoint.

You are browsing the best resource for Online Education.

Sample 2
========
A distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions.

Distributed ledger technology (DLT) includes blockchain technologies and smart contracts.

While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm.

指定された場所に2つのテキストファイルがあり、プログラムはこれら2つのファイルの内容を読み取り、コンソールにテキストを表示しました。


  1. ウィンドウからTkinterウィジェットを削除するにはどうすればよいですか?

    アプリケーションで役に立たないウィジェットを削除したい場合があります。 。破棄を使用して、ウィンドウまたはフレームからウィジェットを削除できます。 tkinterのメソッド。関数を定義することにより、ウィジェットで呼び出すことができます。 例 この例では、ウィンドウからテキストラベルウィジェットを削除するボタンを作成しました。 #Import the tkinter library from tkinter import * #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry(&qu

  2. Pythonでラベルからテキストを削除するにはどうすればよいですか?

    Tkinterは、GUIベースのアプリケーションの作成と開発に使用されるPythonライブラリです。この記事では、テキストが含まれるラベルからテキストを削除する方法を説明します。 ラベルからテキストを削除するために、ラベルのトリガーとして機能する関連ボタンを作成します。 例 #import Tkinter Library from tkinter import * #Create an instance of tkinter frame win= Tk() #Define the size and geometry of the frame win.geometry("700x