Home > Tags > write

write

AIR: テキストファイルに書き込み - openAsync()、writeMultiByte()

AIR: テキストファイルに書き込み
AIRコンポーネントではローカルのファイルにアクセスすることができます。下記のコードは日本語を含むマルチバイトの文字列をテキストファイルに書き込む処理をします。

処理の手順

  1. FileStream#openAsync()かopen()メソッドの引数にFileインスタンスとFileModeのプロパティを設定して実ファイルのパイプに接続
  2. FileStream#writeMultiByte()でファイルに書き込み
  3. FileStream#close()でストリームを閉じる

ソースコード

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" title="シンプルテキストメイカー">
<mx:Script>
  <![CDATA[
  import mx.controls.Alert;

  private var choDir:File = File.documentsDirectory; // ダイアログの初期ディレクトリ
  private var saveFile:File;
  private var stream:FileStream;

  private function onSaveFileBut():void {
    choDir.addEventListener(Event.SELECT, onSelectSaveFile);
    choDir.browseForSave("テキストファイルに保存");
  }

  private function onSelectSaveFile(e:Event):void {
    saveFile = e.target as File; // 選択されたファイル
    choDir.removeEventListener(Event.SELECT, onSelectSaveFile);
    try {
      stream = new FileStream();
      stream.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorWriteFile);
      stream.openAsync(saveFile, FileMode.WRITE); // 書き込みmodeで開く(フツーのopen()でもOK)
      var str:String = txtArea_.text;
      // 改行文字と文字コードをOS標準のものに置き換えて書き込み
      str = str.replace(/\n/g, File.lineEnding);
      stream.writeMultiByte(str, File.systemCharset); // 実際に書き込み
    } catch (err:IOError) {
      progLab_.text = "IOError : " + err;
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
  }

  // ファイル書き込みに失敗した場合
  private function onIOErrorWriteFile(e:IOErrorEvent):void {
    Alert.show("ファイルの書き込みに失敗", "エラー", Alert.OK, this);
    if (stream != null) {
      stream.close();
    }
  }
  ]]>
</mx:Script>
  <mx:VBox x="0" y="0" height="100%" width="100%">
    <mx:HBox width="100%">
      <mx:Button label="ファイルに保存" id="saveBut_" click="onSaveFileBut();"/>
      <mx:Label id="progLab_"/>
    </mx:HBox>
    <mx:TextArea width="100%" height="100%" id="txtArea_"/>
  </mx:VBox>
</mx:WindowedApplication>

リファレンス

Python: テキストファイルの行頭に行番号を追加

コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。

ソースコード

#!/usr/bin/python
# coding: UTF-8

import sys

argvs = sys.argv
argc = len(argvs)
if (argc != 3):
    print 'Usage: $ python %s target_file making_file' % argvs[0]
    quit()
f = open(argvs[1])
lines2 = f.readlines()
f.close()
nf = open(argvs[2], 'w')
i = 1
for line in lines2:
    nf.write('%3d: %s' % (i, line))
    i = i + 1
nf.close()

仮にこのソースコードをfile05a.pyというファイルで保存した場合、使用する際はプロンプトに以下のように打ち込みます。

実行結果

プロンプト

> python file05a.py file05a.py file05a-l.txt

この結果、生成されたファイルが下記になります。

file05a-l.txt

  1: #!/usr/bin/python
  2: # coding: UTF-8
  3:
  4: import sys
  5:
  6: argvs = sys.argv
  7: argc = len(argvs)
  8: if (argc != 3):
  9:     print 'Usage: $ python %s target_file making_file' % argvs[0]
 10:     quit()
 11: f = open(argvs[1])
 12: lines2 = f.readlines()
 13: f.close()
 14: nf = open(argvs[2], 'w')
 15: i = 1
 16: for line in lines2:
 17:     nf.write('%3d: %s' % (i, line))
 18:     i = i + 1
 19: nf.close()

Python: テキストファイルに書き込み - write()、writelines()メソッド

テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。

  • write() - 文字列を引数に取り、ファイルに書き込む。
  • writelines() - シーケンス型を引数に取り、ファイルに書き込む。

write() - 文字列を引数に取り、ファイルに書き込む

ソースコード

#!/usr/bin/python
# coding: UTF-8

# 書き込む文字列
str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""

f = open('text.txt', 'w') # 書き込みモードで開く
f.write(str) # 引数の文字列をファイルに書き込む
f.close() # ファイルを閉じる

実行結果

text.txt

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

writelines() - シーケンス型を引数に取り、ファイルに書き込む

ソースコード

#!/usr/bin/python
# coding: UTF-8

str = """It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on."""
strs = str.split('n') # 一行が一要素(文字列)のリスト

f = open('text.txt', 'w') # 書き込みモードで開く
f.writelines(strs) # シーケンスが引数。
f.close()

実行結果

text.txt

It is meaningless only to think my long further aims idly.It is important to set my aims but at the same time I should confirm my present condition.Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

書き込む際は、シーケンスの各要素の文字列を単に連結するだけです。間には改行も空白文字も含まれません。

そういえば、csv.writerオブジェクトを用いたCSVファイル書き込みにはlineterminatorオプション引数に、任意の連結文字列(言い方よくないね→行の終端文字)を代入できます。主に、環境に合わせた改行文字を代入するのに使います。→Python: CSVファイルに書き込み - csv.writerオブジェクト

リファレンス

Python: CSVファイルに書き込み - csv.writerオブジェクト

試しにチャット履歴をCSVファイルに保存するという場合の例を取り上げます。まぁ実際はメッセンジャーアプリのXMLファイル等をコンバートして保存する例を持ってきた方が良いのかもしれませんが、そうするとコードが長くなり今記事の焦点が合わなくなるので割愛します。

ソースコード

#!/usr/bin/python
# coding: UTF-8

# CSVファイルに書き込み

import csv # CSVファイルを扱うためのモジュールのインポート

filename = "table02.csv"
writecsv = csv.writer(file(filename, 'w'), lineterminator='n') # 書き込みファイルの設定

writecsv.writerow(['2007/11/12 20:19:18', 'や、こんばんは。'])  # 1行(リスト)の書き込み
writecsv.writerow(['2007/11/12 20:19:39', 'おいーす'])
writecsv.writerow(['2007/11/12 20:19:53', '久しぶりだね'])
writecsv.writerow(['2007/11/12 20:20:02', 'そだね。'])

chatable = [['2007/11/12 20:42:58', 'そうだね'],
['2007/11/12 20:43:03', '色々ありがとう'],
['2007/11/12 20:43:12', 'いえ、こちらこそ。'],
['2007/11/12 20:43:21', 'それじゃあまた'],
['2007/11/12 20:43:27', 'うん、またねー。']]
writecsv.writerows(chatable) # 複数行(リストのリスト|テーブル)の書き込み

実行結果 (table02.csv)

2007/11/12 20:19:18,や、こんばんは。
2007/11/12 20:19:39,おいーす
2007/11/12 20:19:53,久しぶりだね
2007/11/12 20:20:02,そだね。
2007/11/12 20:42:58,そうだね
2007/11/12 20:43:03,色々ありがとう
2007/11/12 20:43:12,いえ、こちらこそ。
2007/11/12 20:43:21,それじゃあまた
2007/11/12 20:43:27,うん、またねー。

リファレンス

Home > Tags > write

バックナンバー
最近のコメント
最近のトラックバック
メタ情報

Return to page top