0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python]指定したファイルから値を抽出し、その値を他のファイルに書き込む

Posted at

はじめに

テキストファイルにリストが記載されている中から特定の値を抽出し
その値を他のファイルに書き込むスクリプトを書きました。

ソース

  • 関数

grepWordInTxtFile.py
def grepWordInTxtFile(file_path, targetWords):
 

    with open(file_path) as f:
        lines = f.readlines()

    lines_strip = [line.strip() for line in lines ]
    print(lines_strip)

    list_pork = [line_s for line_s in lines_strip if targetWords in line_s ]
    print(list_pork)

    list_pork_value = [item.split()[1] for item in list_pork ]
    print(list_pork_value[0])
    
    return list_pork_value[0]

  • 呼び出し側

main.py
import grepWordInTxtFile 

inputFilePath = "C:\\PY\\replace\\gredientList.txt"
outputFilePath = "C:\\PY\\replace\\menu.txt"
target = "pork"

gredient =  grepWordInTxtFile.grepWordInTxtFile(inputFilePath, target)

f = open(outputFilePath, 'w')

words = "Today's menu is hamburger using " + str(target) + "!" + " price is " + str(gredient) + "."

f.writelines(words)

f.close()
  • サンプルファイル

gredientList.txt
fish 300
pork 500
avocado 600

結果

menu.txt
Today's menu is hamburger using pork! price is 500.

参考文献

【python】ファイルから文字列や特定行を検索・抽出
数値を文字列に変換して文字列と連結する
関数からreturn文を使って呼び出し元へ戻り値を返す
Pythonのリストからの要素の取り出し(抽出)方法のまとめ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?