Python-マスターファイルに複数のファイルデータを書き込む
ファイル処理は、Webアプリケーションの重要な部分です。
Pythonには、ファイルを作成、読み取り、更新、および削除するためのいくつかの関数があります。
既存のファイルに書き込むには、open()関数にパラメータを追加する必要があります-
「a」-追加-ファイルの最後に追加します
"w"-書き込み-既存のコンテンツを上書きします
例
import os
# list the files in directory
lis = os.listdir('D:\\python' '\\data_files\\data_files')
print(lis)
tgt = os.listdir('D:\\python' '\\data_files\\target_file')
file_dir ='D:\\python\\data_files\\data_files'
out_file = r'D:\\python\\data_files\\target_file\\master.txt'
ct = 0
print('target file :', tgt)
try:
# check for if file exists
# if yes delete the file
# otherwise data will be appended to existing file
if len(tgt)>0:
os.remove('D:\\python' '\\data_files\\target_file\\master.txt')
open(tgt, 'a').close()
else:
# create an empty file
open(tgt, 'a').close()
except:
head = open('D:\\python' '\\data_files\\target_file\\master.txt', 'a+')
line ='empno, ename, sal'
# write header to output
print(head, line)
head.close()
# below loop to write data to output file
for line1 in lis:
f_dir = file_dir+'\\'+line1
# open files in read mode
in_file = open(f_dir, 'r+')
# open output in append mode
w = open(out_file, 'a+')
d = in_file.readline()
d = in_file.readlines()
w.write("\n")
for line2 in d:
print(line2)
w.write(line2)
ct = ct + 1
w.close()
#using pandas
import pandas as pd
# pd.read_csv creates dataframes
df1 = pd.read_csv('D:\python\data_files\data_files\emp_1.txt')
df2 = pd.read_csv('D:\python\data_files\data_files\emp_2.txt')
df3 = pd.read_csv('D:\python\data_files\data_files\emp_3.txt')
frames = [df1, df2, df3]
# concat function concatenates the frames
result = pd.concat(frames)
# to_csv function writes output to file
result.to_csv('D:\\python\\data_files' '\\target_file\\master.txt', encoding ='utf-8', index = False) -
Pythonを使用したBase64データエンコーディング
base64モジュールの関数は、バイナリデータをプレーンテキストプロトコルを使用した送信に適したASCIIのサブセットに変換します。 エンコーディングおよびデコーディング機能は、Base16、Base32、およびBase64アルゴリズムを定義するRFC 3548の仕様と、デファクトスタンダードのAscii85およびBase85エンコーディングの仕様を実装します。 RFC 3548エンコーディングは、バイナリデータのエンコーディングに適しており、電子メールで安全に送信したり、URLの一部として使用したり、HTTPPOSTリクエストの一部として含めたりすることができます。 このモジュールによっ
-
Pythonを使用して複数のファイルの名前を変更する
rename()メソッドは、Python3でファイルまたはディレクトリの名前を変更するために使用されます。 rename()メソッドはosモジュールの一部です。 os.rename()の構文 os.rename(src, dst) 最初の引数は、名前を変更するファイルの送信元アドレスであるsrcであり、2番目の引数は新しい名前の宛先であるdstです。 画像フォルダが1つあるディレクトリを考えてみましょう。ここにこの画像フォルダがあります。 入力 サンプルコード import os # Function to rename multiple files def main():