<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yukun&#039;s Blog &#187; File</title>
	<atom:link href="http://www.yukun.info/blog/tag/file/feed" rel="self" type="application/rss+xml" />
	<link>http://www.yukun.info</link>
	<description>難しいことは分かりやすく、簡単なことは面白く紹介</description>
	<lastBuildDate>Thu, 26 Jan 2012 03:33:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Android: リソースの画像ファイルの拡大・縮小描画 &#8211; drawBitmap()</title>
		<link>http://www.yukun.info/blog/2010/01/android-draw-image-resources.html</link>
		<comments>http://www.yukun.info/blog/2010/01/android-draw-image-resources.html#comments</comments>
		<pubDate>Sat, 02 Jan 2010 12:13:04 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Image]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1446</guid>
		<description><![CDATA[表示する画像はEclipse上でAndroidプロジェクト作成時に自動的に作成されるIcon画像です。 画像パス：プロジェクト名/res/drawable-hdpi/icon.png resフォルダ以下に置かれたリソース &#8230; <a href="http://www.yukun.info/blog/2010/01/android-draw-image-resources.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2010/01/android-draw-image-resources.html">Android: リソースの画像ファイルの拡大・縮小描画 &#8211; drawBitmap()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.yukun.info/wp-content/uploads/android_image_sample01.png"><img src="http://www.yukun.info/wp-content/uploads/android_image_sample01-202x300.png" alt="画像ファイルの表示（拡大・縮小）" title="画像ファイルの表示（拡大・縮小）" width="202" height="300" class="size-medium wp-image-1447" /></a></p>
<p>表示する画像はEclipse上でAndroidプロジェクト作成時に自動的に作成されるIcon画像です。<br />
画像パス：<em>プロジェクト名</em>/res/drawable-hdpi/icon.png</p>
<p>resフォルダ以下に置かれたリソースはコンパイル時にプログラムに組み込まれます。その画像リソースを読み込む際は、</p>
<pre>
Bitmap BitmapFactory.decodeResource(Resources r, int resourcesID)
</pre>
<p>を用います。読み込んだBitmapインスタンスを描画するには、Canvasクラスのインスタンスメソッドである</p>
<pre>
void drawBitmap(Bitmap image, int x, int y, Paint p)
</pre>
<p>を使います。なお、拡大・縮小する場合も上記のdrawBitmapをオーバーロードしたものを使います。</p>
<pre>
void drawBitmap(Bitmap image, Rect src, Rect dst, Paint p)
</pre>
<p>今回のサンプルプログラムでは、元画像の幅と高さを2倍したイメージを描画しています。</p>
<h3>ImageSp.java</h3>
<pre>
package info.yukun.imagesp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class ImageSp extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(new ImageView(this));
	}
}
</pre>
<h3>ImageView.java</h3>
<pre>
package info.yukun.imagesp;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.View;

public class ImageView extends View {

	private Bitmap image;

	public ImageView(Context context) {
		super(context);
		setBackgroundColor(Color.WHITE);

		// リソースの画像ファイルの読み込み
		Resources r = context.getResources();
		image = BitmapFactory.decodeResource(r, R.drawable.icon);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// イメージ描画
		canvas.drawBitmap(image, 0, 0, null);

		int w = image.getWidth();
		int h = image.getHeight();
		// 描画元の矩形イメージ
		Rect src = new Rect(0, 0, w, h);
		// 描画先の矩形イメージ
		Rect dst = new Rect(0, 200, w*2, 200 + h*2);
		canvas.drawBitmap(image, src, dst, null);
	}
}
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/11/actionscript-flash-load-server-image-file.html" rel="bookmark" title="2008年11月21日">ActionScript: 画像ファイルをダウンロードして表示 &#8211; Loaderクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/10/android-integer-to-binary-string.html" rel="bookmark" title="2008年10月29日">Android: 10進数→2進数変換アプリ</a></li>
<li><a href="http://www.yukun.info/blog/2010/06/android-unable-to-open-sync-connection.html" rel="bookmark" title="2010年6月5日">Android: &#8220;Unable to open sync connection!&#8221; の対処例</a></li>
<li><a href="http://www.yukun.info/blog/2010/03/android-mksdcard-could-not-create-file-aborting.html" rel="bookmark" title="2010年3月14日">Android: mksdcardコマンドのabortingの解決法 &#8211; could not create file &#8216;&#8230;&#8217;, aborting&#8230;</a></li>
<li><a href="http://www.yukun.info/blog/2012/01/android-eclipse-build-error.html" rel="bookmark" title="2012年1月6日">Android: Eclipseビルドエラーの対処例 &#8211; Error generating final archive</a></li>
</ul>
<p><!-- Similar Posts took 9.603 ms --></p>
<p><a href="http://www.yukun.info/blog/2010/01/android-draw-image-resources.html">Android: リソースの画像ファイルの拡大・縮小描画 &#8211; drawBitmap()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2010/01/android-draw-image-resources.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</title>
		<link>http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html</link>
		<comments>http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html#comments</comments>
		<pubDate>Wed, 17 Dec 2008 15:00:26 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[AIR]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1272</guid>
		<description><![CDATA[AIRコンポーネントではローカルのファイルにアクセスすることができます。下記のコードは日本語を含むマルチバイトの文字列をテキストファイルに書き込む処理をします。 処理の手順 FileStream#openAsync()か &#8230; <a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html">AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.yukun.info/wp-content/uploads/WriteTxtFile01_result.png"><img src="http://www.yukun.info/wp-content/uploads/WriteTxtFile01_result-e1273382752288.png" alt="AIR: テキストファイルに書き込み" title="WriteTxtFile01_result" width="400" height="328" class="size-full wp-image-1533" /></a></p>
<p>AIRコンポーネントではローカルのファイルにアクセスすることができます。下記のコードは日本語を含むマルチバイトの文字列をテキストファイルに書き込む処理をします。</p>
<h2>処理の手順</h2>
<ol>
<li>FileStream#openAsync()かopen()メソッドの引数にFileインスタンスとFileModeのプロパティを設定して実ファイルのパイプに接続</li>
<li>FileStream#writeMultiByte()でファイルに書き込み</li>
<li>FileStream#close()でストリームを閉じる</li>
</ol>
<h3>ソースコード</h3>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:WindowedApplication xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot; title=&quot;シンプルテキストメイカー&quot;&gt;
&lt;mx:Script&gt;
  &lt;![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(&quot;テキストファイルに保存&quot;);
  }

  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 = &quot;IOError : &quot; + err;
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
  }

  // ファイル書き込みに失敗した場合
  private function onIOErrorWriteFile(e:IOErrorEvent):void {
    Alert.show(&quot;ファイルの書き込みに失敗&quot;, &quot;エラー&quot;, Alert.OK, this);
    if (stream != null) {
      stream.close();
    }
  }
  ]]&gt;
&lt;/mx:Script&gt;
  &lt;mx:VBox x=&quot;0&quot; y=&quot;0&quot; height=&quot;100%&quot; width=&quot;100%&quot;&gt;
    &lt;mx:HBox width=&quot;100%&quot;&gt;
      &lt;mx:Button label=&quot;ファイルに保存&quot; id=&quot;saveBut_&quot; click=&quot;onSaveFileBut();&quot;/&gt;
      &lt;mx:Label id=&quot;progLab_&quot;/&gt;
    &lt;/mx:HBox&gt;
    &lt;mx:TextArea width=&quot;100%&quot; height=&quot;100%&quot; id=&quot;txtArea_&quot;/&gt;
  &lt;/mx:VBox&gt;
&lt;/mx:WindowedApplication&gt;
</pre>
<h3>リファレンス</h3>
<ul>
<li><a href="http://help.adobe.com/ja_JP/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7e4a.html" title="Adobe AIR 1.5 * ファイルシステムの操作" target="_blank">Adobe AIR 1.5 * ファイルシステムの操作</a></li>
<li><a href="http://help.adobe.com/ja_JP/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc2.html" title="Adobe AIR 1.5 * ファイルの読み取りと書き込み" target="_blank">Adobe AIR 1.5 * ファイルの読み取りと書き込み</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html" rel="bookmark" title="2008年12月17日">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" rel="bookmark" title="2008年6月18日">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/air-actionscript-sqlite-statement.html" rel="bookmark" title="2008年12月22日">AIR: SQLiteでデータの挿入と検索 &#8211; SQLConnection、SQLStatementクラス</a></li>
</ul>
<p><!-- Similar Posts took 8.837 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html">AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</title>
		<link>http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html</link>
		<comments>http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html#comments</comments>
		<pubDate>Wed, 17 Dec 2008 03:30:27 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[AIR]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1269</guid>
		<description><![CDATA[AIRコンポーネントではローカルのファイルにアクセスすることができます。下記のコードは日本語を含むマルチバイトのテキストファイルを読み込み、画面い表示する処理を行います。 大まかな手順 FileStreamのコンストラク &#8230; <a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.yukun.info/wp-content/uploads/ReadTxtFile01_result.png"><img src="http://www.yukun.info/wp-content/uploads/ReadTxtFile01_result-e1273382664744.png" alt="AIR: テキストファイル読み込みの実行結果" title="ReadTxtFile01_result" width="400" height="328" class="size-full wp-image-1531" /></a></p>
<p>AIRコンポーネントではローカルのファイルにアクセスすることができます。下記のコードは日本語を含むマルチバイトのテキストファイルを読み込み、画面い表示する処理を行います。</p>
<h2>大まかな手順</h2>
<ol>
<li>FileStreamのコンストラクタの引数に対象のファイルへのパスが設定されたFileインスタンスを渡す。</li>
<li>FileStream#openAsyncで実ファイルへのパイプ接続。</li>
<li>この時、非同期の読み込み完了／エラーを取得するためにイベントを登録しておく。</li>
<li>実際の文字の読み取り（どれだけ読むか、文字コードの変換など）はFileStream#readMultiByteで行う。</li>
<li>ストリームのインスタンスには接続時にpositionプロパティ（何処読んでいるかのポインタみたいなもの）からファイル末尾までのサイズ（bytesAvailable）を取得してるので、読み込みサイズにそれを指定。</li>
<li>FileStream#close()でストリームを閉じる</li>
</ol>
<h3>ソースコード</h3>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:WindowedApplication xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot;
  title=&quot;テキストビュワー&quot;&gt;
  &lt;mx:Script&gt;
    &lt;![CDATA[
    import flash.filesystem.*;
    import mx.events.*;
    import mx.controls.Alert;

    private var choDir:File = File.documentsDirectory; // 開くディレクトリを指す
    private var curFile:File; // 選択されたファイル
    private var stream:FileStream;

    private function onOpenFileBut():void {
      choDir.addEventListener(Event.SELECT, onSelectFile);
      choDir.browseForOpen(&quot;開く&quot;); // ファイル選択ダイアログの表示
    }

    // ファイルが選択されたイベント
    private function onSelectFile(e:Event):void {
      txtArea_.text = &quot;&quot;;
      stream = new FileStream();
      curFile = e.target as File;
      stream.addEventListener(Event.COMPLETE, onCompleteReadFile);
      stream.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorReadFile);
      stream.addEventListener(ProgressEvent.PROGRESS, onProgReadFile);
      stream.openAsync(curFile, FileMode.READ); // 非同期読み込み
      curFile.removeEventListener(Event.SELECT, onSelectFile);
    }

    private function onCompleteReadFile(e:Event):void {
      try {
        // OS標準の文字コードで読み込み
        var str:String = stream.readMultiByte(stream.bytesAvailable, File.systemCharset);
        // OS標準の改行文字への変換
        var pat:RegExp = new RegExp(File.lineEnding, &quot;g&quot;);
        str = str.replace(pat, &quot;n&quot;);
        txtArea_.text = str; // テキストエリアに表示
        stream.removeEventListener(Event.COMPLETE, onCompleteReadFile);
        stream.removeEventListener(IOErrorEvent.IO_ERROR, onIOErrorReadFile);
        stream.removeEventListener(ProgressEvent.PROGRESS, onProgReadFile);
      } catch (err:Error) {
        progLab_.text = &quot;IOError: &quot; + err;
      }
      finally {
        // パイプのクローズ
        if (stream != null) {
          stream.close();
        }
      }
    }

    private function onIOErrorReadFile(e:IOErrorEvent):void {
      Alert.show(&quot;ファイルを読み込み不可&quot;, &quot;Error&quot;, Alert.OK, this); // 第4引数には親オブジェトを渡す
      if (stream != null) {
        stream.close();
      }
    }

    private function onProgReadFile(e:ProgressEvent):void {
      progLab_.text = &quot;Progress: &quot; +  e.bytesLoaded + &quot; / &quot; + e.bytesTotal + &quot; bytes&quot;;
    }
    ]]&gt;
  &lt;/mx:Script&gt;
  &lt;mx:VBox x=&quot;0&quot; y=&quot;0&quot; height=&quot;100%&quot; width=&quot;100%&quot;&gt;
    &lt;mx:HBox width=&quot;100%&quot;&gt;
      &lt;mx:Button label=&quot;ファイルを開く&quot; id=&quot;openBut_&quot; click=&quot;onOpenFileBut();&quot;/&gt;
      &lt;mx:Label id=&quot;progLab_&quot;/&gt;
    &lt;/mx:HBox&gt;
    &lt;mx:TextArea width=&quot;100%&quot; height=&quot;100%&quot; id=&quot;txtArea_&quot;/&gt;
  &lt;/mx:VBox&gt;

&lt;/mx:WindowedApplication&gt;
</pre>
<h3>リファレンス</h3>
<ul>
<li><a href="http://help.adobe.com/ja_JP/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc8.html" title="Adobe AIR 1.5 * ファイルの読み取りと書き込みのワークフロー" target="_blank">Adobe AIR 1.5 * ファイルの読み取りと書き込みのワークフロー</a></li>
<li><a href="http://help.adobe.com/ja_JP/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7dac.html" title="Adobe AIR 1.5 * 読み取りバッファと FileStream オブジェクトの bytesAvailable プロパティ" target="_blank">Adobe AIR 1.5 * 読み取りバッファと FileStream オブジェクトの bytesAvailable プロパティ</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html" rel="bookmark" title="2008年12月18日">AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
</ul>
<p><!-- Similar Posts took 14.511 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</title>
		<link>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html#comments</comments>
		<pubDate>Thu, 18 Sep 2008 11:40:50 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1191</guid>
		<description><![CDATA[ファイルのパスや名前のミス、パーミッションの権限が無い等が原因でファイルを読み込めない場合があります。そのような場合、すなわち例外が発生した際にそこで処理を中断して、発生した例外に合わせた処理ブロックにジャンプする構文が &#8230; <a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>ファイルのパスや名前のミス、パーミッションの権限が無い等が原因でファイルを読み込めない場合があります。そのような場合、すなわち例外が発生した際にそこで処理を中断して、発生した例外に合わせた処理ブロックにジャンプする構文が、try:～except Error:～構文です。</p>
<p>今回は、コマンドライン引数で英文テキストファイル名を指定し、スクリプト内でファイル内容を読み込み、単語数をカウントし出力するスクリプトを以って、オプションのelse、finallyブロックを含めた例外ブロックの扱いを確認します。<br />
ただし、ここでの「単語」とは、１つの空白文字で区切られた文字列とします（簡単に）。</p>
<h2>ソースコード</h2>
<pre>
# -*- coding: UTF-8 -*-

import sys

script_name = sys.argv[0]
try:
    arg = sys.argv[1]
    f = open(arg, 'r')
except IndexError:
    print 'Usage: %s TEXTFILE' % script_name
except IOError:
    print '"%s" cannot be opened.' % arg
else:
    print arg, 'contains', len(f.read().split(' ')), 'words.'
    f.close()
finally:
    print 'n"%s" process end.' % script_name
    quit()
print 'Not reach this line.'
</pre>
<h2>コードの説明</h2>
<h3>tryブロック</h3>
<p>まず、例外を発生させる恐れのある行は、tryブロック内に書きます。</p>
<p>ここで発生しそうなのは、コマンドライン引数が格納されているリストへのアクセス部分であるsys.argv[1]です。[]演算子で存在しない要素を参照するエラー、もとい例外が発生する恐れがあります。</p>
<p>また、ファイルを開くopen(arg, &#8216;r&#8217;)も冒頭の理由で例外を発生させるかもしれません。</p>
<h3>exceptブロック</h3>
<p>exceptブロックは、tryブロックで例外が発生した場合にのみ実行されるブロックです。その為、例外が発生しない場合は実行されません。</p>
<p>発生する可能性のある例外のタイプ毎にexceptブロックを書けば、そのタイプ毎の例外への対処処理を書くことが出来ます。</p>
<pre>
except <em>TYPE_A</em>Error:
    <em>TYPE_A</em>Errorが発生した際のとある処理...
except <em>TYPE_B</em>Error:
    <em>TYPE_B</em>Errorが発生した際のとある処理...
</pre>
<h3>elseブロック　（オプション）</h3>
<p>elseブロックは全てのexceptブロックの後に書きます（任意なので書かなくても構わない）。</p>
<p>elseブロックはtryブロックで例外が発生<strong>しなかった場合にのみ</strong>実行されるブロックです。今回は、ファイルの読み込みとクローズに使用しています。</p>
<h3>finallyブロック　（オプション）</h3>
<p>finallyブロックはtryブロックで例外が発生<strong>するしないに関わらず</strong>実行されるブロックです（任意なので書かなくても構わない）。</p>
<h2>実行結果</h2>
<p>読み込むテキストファイルを以下の<em>aLine.txt</em>とします。<br />
<em>aLine.txt</em></p>
<pre>
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<h3>コマンドラインで適切な引数を与えた場合</h3>
<pre>
$ python excp01.py aLine.txt
aLine.txt contains 22 words.

"excp01.py" process end.
</pre>
<h3>存在しないファイル名を引数を与えた場合</h3>
<pre>
$ python excp01.py texfile.tex
"texfile.tex" cannot be opened.

"excp01.py" process end.
</pre>
<h3>コマンドライン引数を与えなかった場合</h3>
<pre>
$ python excp01.py
Usage: excp01.py TEXTFILE

"excp01.py" process end.
</pre>
<h2>例外オブジェクト名をpython処理系に聞いてみる</h2>
<p>どんなメソッドや関数、演算子が、どのような例外を投げるのか予測が付かない場合があるかと思います。<br />
そんな場合でもとりあえずスクリプトを実行してエラーを確認してみましょう。<br />
<code>SyntaxError: invalid syntax</code>以外のエラーがある場合、例えば、</p>
<pre>
$ python excp01.py
Traceback (most recent call last):
  File "excp01.py", line 5, in <module>
    arg = sys.argv[1]
IndexError: list index out of range
</pre>
<p>のような場合は、最終行の行頭のIndexErrorが例外名となります。</p>
<h2>何でも例外任せにしていいの？</h2>
<p>計算量からみてあまり良いとは言えません。今プログラムのコマンドライン引数の確認を、<br />
<code>if len(sys.argv) != 2: ホニャララ</code><br />
とすると整数の比較ですみますが、例外のキャッチに任せると、例外インスタンスを生成し送出するという、結構な計算量がかかります。ネットワーク接続やファイル読み書きなどのIOでは有効ですが、それ以外では積極的に使わないほうがいいかもしれません。</p>
<h2>ドキュメント</h2>
<ul>
<li><a href="http://docs.python.org/lib/module-exceptions.html" title="2.3 Built-in Exceptions" target="_blank">2.3 Built-in Exceptions</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html" rel="bookmark" title="2008年8月9日">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a></li>
</ul>
<p><!-- Similar Posts took 10.019 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rで統計: CSVファイルの読み込み &#8211; read.csv()メソッド</title>
		<link>http://www.yukun.info/blog/2008/09/r-read-csv-file.html</link>
		<comments>http://www.yukun.info/blog/2008/09/r-read-csv-file.html#comments</comments>
		<pubDate>Wed, 10 Sep 2008 12:50:31 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[R]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://blog.yukun.info/?p=583</guid>
		<description><![CDATA[読み込むCSVファイルは2007年度のセリーグの打撃成績の順位です。 参考：2007年度 セントラル・リーグ 個人打撃成績（規定打席以上） batting2007.csv 順位,打率,安打 1,0.346,193 2,0 &#8230; <a href="http://www.yukun.info/blog/2008/09/r-read-csv-file.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/r-read-csv-file.html">Rで統計: CSVファイルの読み込み &#8211; read.csv()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>読み込むCSVファイルは2007年度のセリーグの打撃成績の順位です。</p>
<p>参考：<a href="http://bis.npb.or.jp/2007/stats/bat_c.html" title="2007年度 セントラル・リーグ 個人打撃成績（規定打席以上）" target="_blank">2007年度 セントラル・リーグ 個人打撃成績（規定打席以上）</a></p>
<p><em>batting2007.csv</em></p>
<pre>
順位,打率,安打
1,0.346,193
2,0.343,204
3,0.318,172
4,0.313,177
5,0.31,175
6,0.308,155
7,0.302,122
8,0.302,118
9,0.3,120
10,0.3,139
</pre>
<h2>プロンプト</h2>
<pre>
> read.csv("batting2007.csv")
   順位  打率 安打
1     1 0.346  193
2     2 0.343  204
3     3 0.318  172
4     4 0.313  177
5     5 0.310  175
6     6 0.308  155
7     7 0.302  122
8     8 0.302  118
9     9 0.300  120
10   10 0.300  139
> batting$安打
 [1] 193 204 172 177 175 155 122 118 120 139
</pre>
<p>read.csv()メソッドでCSVファイルを読み込み、そのデータフレームをbatting変数に格納しています。</p>
<p>実行結果を見ると、ファイル1行目のフィールド(列)名が変数名を表し、2行目以降がテーブル本体を表していることが分かります。これによって、例えば安打の列を抽出したい場合は、batting$安打と指定すればOKです。</p>
<p>ただ、毎回々々「batting$安打」と指定するのは億劫ですので、以下のコマンドで簡略化します。</p>
<pre>
> attach(batting)
> 安打
 [1] 193 204 172 177 175 155 122 118 120 139
>
</pre>
<p>attach()関数によってワークスペースにオブジェクトが保存され、データフレーム内の変数名のみでのアクセスが可能になります。</p>
<h2>read.csv()メソッドのheader引数にFALSEを指定した場合</h2>
<p>read.csv()メソッドはデフォルトでheader引数にTRUEが指定されていますが、以下のようにFALSE（必ず大文字）を指定することも出来ます。その場合の動作は以下のようになります。</p>
<pre>
> batting <- read.csv("batting2007.csv", header=FALSE)
> batting
     V1    V2   V3
1  順位  打率 安打
2     1 0.346  193
3     2 0.343  204
4     3 0.318  172
5     4 0.313  177
6     5  0.31  175
7     6 0.308  155
8     7 0.302  122
9     8 0.302  118
10    9   0.3  120
11   10   0.3  139
> batting$V3
 [1] 安打 193  204  172  177  175  155  122  118  120  139
Levels: 118 120 122 139 155 172 175 177 193 204 安打
>
</pre>
<p>ファイル1行目の列名がテーブル本体のデータセットに組み込まれていることが分かります。この場合の列へのアクセスは上の実行結果から、batting$V3と分かります。フィールド(列)名（一行目）を省略したCSVファイルを読み込みたい場合にはこのオプション引数を指定します。</p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/r-read-source-file.html" rel="bookmark" title="2008年9月5日">Rで統計: *.Rソースファイルの読み込みと実行 &#8211; source()関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" rel="bookmark" title="2008年6月18日">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></li>
</ul>
<p><!-- Similar Posts took 7.958 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/r-read-csv-file.html">Rで統計: CSVファイルの読み込み &#8211; read.csv()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/r-read-csv-file.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python: テキストファイルの行頭に行番号を追加</title>
		<link>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html#comments</comments>
		<pubDate>Mon, 08 Sep 2008 12:50:42 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1017</guid>
		<description><![CDATA[コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。 ソースコード #!/usr/bin/python # coding: UTF-8 import sy &#8230; <a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。</p>
<h3>ソースコード</h3>
<pre>
#!/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()
</pre>
<p>仮にこのソースコードをfile05a.pyというファイルで保存した場合、使用する際はプロンプトに以下のように打ち込みます。</p>
<h3>実行結果</h3>
<h4>プロンプト</h4>
<pre>
> python file05a.py file05a.py file05a-l.txt
</pre>
<p>この結果、生成されたファイルが下記になります。</p>
<h4>file05a-l.txt</h4>
<pre>
  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()
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html" rel="bookmark" title="2008年9月18日">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a></li>
</ul>
<p><!-- Similar Posts took 9.236 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</title>
		<link>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html#comments</comments>
		<pubDate>Sat, 06 Sep 2008 12:50:16 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=817</guid>
		<description><![CDATA[テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。 write() &#8211; 文字列を引数に取り、ファイルに書き込む。 writelines() &#8211; シーケンス &#8230; <a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>テキストファイルへの書き込み処理をFileオブジェクトの以下のメソッドを用いて書いてみます。</p>
<ul>
<li>write() &#8211; 文字列を引数に取り、ファイルに書き込む。</li>
<li>writelines() &#8211; シーケンス型を引数に取り、ファイルに書き込む。</li>
</ul>
<h2>write() &#8211; 文字列を引数に取り、ファイルに書き込む</h2>
<h3>ソースコード</h3>
<pre>
#!/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() # ファイルを閉じる
</pre>
<h3>実行結果</h3>
<p><em>text.txt</em></p>
<pre>
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.
</pre>
<h2>writelines() &#8211; シーケンス型を引数に取り、ファイルに書き込む</h2>
<h3>ソースコード</h3>
<pre>
#!/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()
</pre>
<h3>実行結果</h3>
<p><em>text.txt</em></p>
<pre>
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.
</pre>
<p>書き込む際は、シーケンスの各要素の文字列を単に連結するだけです。間には改行も空白文字も含まれません。</p>
<p>そういえば、csv.writerオブジェクトを用いたCSVファイル書き込みにはlineterminatorオプション引数に、任意の連結文字列(言い方よくないね→行の終端文字)を代入できます。主に、環境に合わせた改行文字を代入するのに使います。→<a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" title="Python: CSVファイルに書き込み - csv.writerオブジェクト - Yukun's Blog">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></p>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/built-in-funcs.html" title="2.1 Built-in Functions" target="_blank">2.1 Built-in Functions</a></li>
<li><a href="http://docs.python.org/lib/bltin-file-objects.html" title="3.9 File Objects" target="_blank">3.9 File Objects</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-write-text.html" rel="bookmark" title="2008年12月18日">AIR: テキストファイルに書き込み &#8211; openAsync()、writeMultiByte()</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-write.html" rel="bookmark" title="2008年6月18日">Python: CSVファイルに書き込み &#8211; csv.writerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
</ul>
<p><!-- Similar Posts took 9.781 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-file-write-writelines.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rで統計: *.Rソースファイルの読み込みと実行 &#8211; source()関数</title>
		<link>http://www.yukun.info/blog/2008/09/r-read-source-file.html</link>
		<comments>http://www.yukun.info/blog/2008/09/r-read-source-file.html#comments</comments>
		<pubDate>Thu, 04 Sep 2008 15:00:01 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[R]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://blog.yukun.info/?p=581</guid>
		<description><![CDATA[これまでの例は数行のコマンドでしたのでプロンプトに直接を打っていましたが、何十行というロジックをプロンプトに順々に打っていくのは非効率です。今回は、予め外部のテキストファイルにソースコードを書き、そのファイルをプロンプト &#8230; <a href="http://www.yukun.info/blog/2008/09/r-read-source-file.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/r-read-source-file.html">Rで統計: *.Rソースファイルの読み込みと実行 &#8211; source()関数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>これまでの例は数行のコマンドでしたのでプロンプトに直接を打っていましたが、何十行というロジックをプロンプトに順々に打っていくのは非効率です。今回は、予め外部のテキストファイルにソースコードを書き、そのファイルをプロンプトから呼び出す手順を次の例で示します。</p>
<p>以下のソースコードを拡張子Rのテキストファイルで保存し、プロンプトから読み込んで実行してみましょう。</p>
<p><em>test.R</em></p>
<pre>
batting2007 <- c(193, 204, 172, 177, 175, 155, 122, 118, 120, 139)
print(batting2007)
</pre>
<p>このテキストファイルを作業ディレクトリにおきます。なお、作業ディレクトリの設定方法はこちらをご覧ください。→<a href="http://www.yukun.info/blog/2008/09/r-set-work-directory.html" title="Rで統計: 作業ディレクトリの設定と確認 - setwd()、getwd()関数 - Yukun's Blog">作業ディレクトリの設定と確認 - setwd()、getwd()関数</a></p>
<h2>プロンプト</h2>
<pre>
> source("test.R")
 [1] 193 204 172 177 175 155 122 118 120 139
>
</pre>
<p>print()関数を用いて画面へ出力しています。</p>
<p>ここで、この状態のままプロンプトで以下のように入力すると、</p>
<pre>
> summary(batting2007)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  118.0   126.2   163.5   157.5   176.5   204.0
> mean(batting2007)
[1] 157.5
>
</pre>
<p>このように、読み込んだソースファイル中の変数が使えることが分かります。これは、関数宣言等を別ファイルに保存し、プロンプトから呼び出したい場合によく使います。</p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/r-read-csv-file.html" rel="bookmark" title="2008年9月10日">Rで統計: CSVファイルの読み込み &#8211; read.csv()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html" rel="bookmark" title="2008年12月17日">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
</ul>
<p><!-- Similar Posts took 11.034 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/r-read-source-file.html">Rで統計: *.Rソースファイルの読み込みと実行 &#8211; source()関数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/r-read-source-file.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: 指定したパスのディレクトリ中のファイル一覧を出力</title>
		<link>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html</link>
		<comments>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html#comments</comments>
		<pubDate>Fri, 08 Aug 2008 15:00:19 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://blog.yukun.info/?p=424</guid>
		<description><![CDATA[あるディレクトリから特定のファイルを検索したい場合、探索対象ディレクトリ内のファイルを全て取得する必要があります。今回は、引数にディレクトリを指すパスを指定することによって、そのディレクトリの内容を取得する関数を2つ示し &#8230; <a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>あるディレクトリから特定のファイルを検索したい場合、探索対象ディレクトリ内のファイルを全て取得する必要があります。今回は、引数にディレクトリを指すパスを指定することによって、そのディレクトリの内容を取得する関数を2つ示します。</p>
<h3>ソースコード</h3>
<pre>
# coding: Shift_JIS

import os # osモジュールのインポート

# os.listdir('パス')
# 指定したパス内の全てのファイルとディレクトリを要素とするリストを返す
files = os.listdir('C:\Python25\')

for file in files:
    print file
</pre>
<h3>実行結果の一例</h3>
<pre>
DLLs
Doc
include
Lib
libs
LICENSE.txt
lxml-wininst.log
NEWS.txt
PIL-wininst.log
pysqlite-wininst.log
pysqlite2-doc
python.exe
pythonw.exe
README.txt
Removelxml.exe
RemovePIL.exe
Removepysqlite.exe
Scripts
tcl
Tools
w9xpopen.exe
</pre>
<h2>ワイルドカードでリスティング対象を指定</h2>
<p>globモジュールのglob()関数の引数内にワイルドカード「*」を含めることが出来ます。これによって、より手軽に目的のファイルを探索することが出来ます。</p>
<h3>ソースコード</h3>
<pre>
# coding: Shift_JIS

import glob

# パス内の全ての"指定パス+ファイル名"と"指定パス+ディレクトリ名"を要素とするリストを返す
files = glob.glob('C:\Python25\*.*') # ワイルドカードが使用可能

for file in files:
    print file
</pre>
<p>os.listdir()と異なり、glob.glob()は取得したファイル文字列には先頭に探査ディレクトリ(引数)のパスが付いています。</p>
<h3>実行結果の一例</h3>
<p><code><br />
C:Python25LICENSE.txt<br />
C:Python25lxml-wininst.log<br />
C:Python25NEWS.txt<br />
C:Python25PIL-wininst.log<br />
C:Python25pysqlite-wininst.log<br />
C:Python25python.exe<br />
C:Python25pythonw.exe<br />
C:Python25README.txt<br />
C:Python25Removelxml.exe<br />
C:Python25RemovePIL.exe<br />
C:Python25Removepysqlite.exe<br />
C:Python25w9xpopen.exe<br />
</code></p>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/module-glob.html" title="11.7 glob -- Unix style pathname pattern expansion" target="_blank">11.7 glob &#8212; Unix style pathname pattern expansion</a></li>
<li><a href="http://docs.python.org/lib/os-file-dir.html" title="14.1.4 Files and Directories" target="_blank">14.1.4 Files and Directories</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/r-set-work-directory.html" rel="bookmark" title="2008年9月3日">Rで統計: 作業ディレクトリの設定と確認 &#8211; setwd()、getwd()関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/linux-users.html" rel="bookmark" title="2008年6月26日">ユーザー管理に関するLinuxコマンド</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-async-read-text.html" rel="bookmark" title="2008年12月17日">AIR: テキストファイルを非同期に読み込む &#8211; openAsync()、readMultiByte()</a></li>
</ul>
<p><!-- Similar Posts took 9.402 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/08/python-directory-listdir-glob.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: コマンドライン引数の取得 &#8211; sys.argv変数</title>
		<link>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html</link>
		<comments>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html#comments</comments>
		<pubDate>Fri, 25 Jul 2008 15:00:55 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=213</guid>
		<description><![CDATA[コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は sys モジュールの argv 属性に文字列を要素とするリストとして格納されています。そして、 &#8230; <a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は <strong>sys モジュールの argv 属性に文字列を要素とするリスト</strong>として格納されています。そして、リストの先頭要素(sys.argv[0])はスクリプトファイル名となっています。</p>
<h2>ソースコード</h2>
<pre>
# coding: Shift_JIS

import sys # モジュール属性 argv を取得するため

argvs = sys.argv  # コマンドライン引数を格納したリストの取得
argc = len(argvs) # 引数の個数
# デバッグプリント
print argvs
print argc
print
if (argc != 2):   # 引数が足りない場合は、その旨を表示
    print 'Usage: # python %s filename' % argvs[0]
    quit()         # プログラムの終了

print 'The content of %s ...n' % argvs[1]
f = open(argvs[1])
line = f.readline() # 1行読み込む(改行文字も含まれる)
while line:
    print line
    line = f.readline()
f.close
</pre>
<h4>text.txt</h4>
<pre>
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.
</pre>
<h2>実行結果</h2>
<h3>引数を指定しない場合</h3>
<pre>
$ python argv01.py
['argv01.py']
1

Usage: # python SCRIPTNAME.py filename
</pre>
<h3>引数を指定した場合</h3>
<pre>
$ python argv01.py text.txt
['argv01.py', 'text.txt']
2

The content of 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.
</pre>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/tut/node12.html" title="10. Brief Tour of the Standard Library" target="_blank">10. Brief Tour of the Standard Library</a>
<ul>
<li><a href="http://docs.python.org/tut/node12.html#SECTION0012300000000000000000" title="10.3 Command Line Arguments" target="_blank">10.3 Command Line Arguments</a></li>
</ul>
</li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html" rel="bookmark" title="2008年9月18日">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
</ul>
<p><!-- Similar Posts took 19.645 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

