<?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; read</title>
	<atom:link href="http://www.yukun.info/blog/tag/read/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>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 8.599 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>人工無脳を作ってみる (1)入力文の末尾に文字列を追加</title>
		<link>http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html</link>
		<comments>http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html#comments</comments>
		<pubDate>Sun, 02 Nov 2008 15:00:46 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Chatterbot]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1233</guid>
		<description><![CDATA[さて、最初は単純にユーザの入力文の末尾に予め定義されている文字列を付け足して応答するだけのものです。 ソースコード package info.yukun.chatterbot; import java.io.Buffer &#8230; <a href="http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html">人工無脳を作ってみる (1)入力文の末尾に文字列を追加</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>
package info.yukun.chatterbot;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SimpleChatterBot {
  private String botName = &quot;chatterbot&quot;;
  private String callStr = &quot;なにかしゃべってよ(&gt;_&lt;)&quot;;
  private String[] suffixResponses = {
    &quot;ってアレですね、わかります(^^)b&quot;,
    &quot;ですか？わかりません(&gt;_&lt;)&quot;,
    &quot;って何？日本語でおk(&#039;`)b&quot;};

  public void go() {
    try {
      BufferedReader stdReader = new BufferedReader(new InputStreamReader(System.in));
      System.out.print(&quot;INPUT : &quot;);
      String response;
      String input;
      while ((input = stdReader.readLine()) != null) { // ユーザの入力待ち
        if (input.equals(&quot;&quot;)) { // 入力が無かった
          response = callStr;
        } else {
          response = decorateInput(input) + getSuffixResponse();
        }
        System.out.print(botName + &quot;: &quot; + response);
        System.out.print(&quot;\nINPUT : &quot;);
      }
      stdReader.close();
      System.out.println(&quot;\nPROGRAM END&quot;);
    } catch (Exception e) {
      e.getStackTrace();
      System.exit(-1); // プログラムを終了
    }
  }

  private String getSuffixResponse() {
    int rand = (int) (Math.random() * suffixResponses.length);
    return suffixResponses[rand];
  }

  private String decorateInput(String input) {
    return &quot;「&quot; + input + &quot;」&quot;;
  }

  public static void main(String[] args) {
    SimpleChatterBot bot = new SimpleChatterBot();
    bot.go();
  }
}
</pre>
<p>getSuffixResponse()メソッド内で使われているMath.random()は、<br />
<blockquote cite="http://sdc.sun.co.jp/java/docs/j2se/1.4/ja/docs/ja/api/java/lang/Math.html" title="Math (Java 2 プラットフォーム SE v1.4.0)">static double random()<br />
0.0 以上で、1.0 より小さい正の符号の付いた double 値を返します。</p></blockquote>
<p>ですので、「Math.random() * 配列の長さ」 は「0～配列の長さ-1」 を意味します。</p>
<h3>実行結果の例</h3>
<pre>
INPUT : こんにちは
chatterbot: 「こんにちは」って何？日本語でおk('`)b
INPUT : え、
chatterbot: 「え、」ですか？わかりません(>_<)
INPUT : いえ、聞き返しただけです。
chatterbot: 「いえ、聞き返しただけです。」って何？日本語でおk('`)b
INPUT :
chatterbot: なにかしゃべってよ(>_<)
INPUT : 最近どうですか？
chatterbot: 「最近どうですか？」ってアレですね、わかります(^^)b
INPUT :
PROGRAM END
</pre>
<p>なんだかー、それはかとなくばかにしていますねf^^;</p>
<p>最初はJavaで書いていきますが、実装する機能の種類やリリースする環境によっては恐らく途中でOOをサポートする他の言語に変更するかも。<br />
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html" rel="bookmark" title="2008年11月2日">Java: ユーザからの(標準)入力を取得 &#8211; System.inとInputStreamReaderクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/03/diff-java-ruby-string.html" rel="bookmark" title="2008年3月4日">JavaとRubyで文字列の終端の扱いの違い</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-strip.html" rel="bookmark" title="2008年5月29日">Java: 文字列の先頭・末尾の文字を削除するstrip()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-intersection.html" rel="bookmark" title="2008年5月20日">検索エンジンを実装 (4)AND演算</a></li>
<li><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html" rel="bookmark" title="2010年5月16日">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a></li>
</ul>
<p><!-- Similar Posts took 7.998 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html">人工無脳を作ってみる (1)入力文の末尾に文字列を追加</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/11/implement-chatterbot-append-suffix.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: ユーザからの(標準)入力を取得 &#8211; System.inとInputStreamReaderクラス</title>
		<link>http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html</link>
		<comments>http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html#comments</comments>
		<pubDate>Sun, 02 Nov 2008 12:00:11 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1232</guid>
		<description><![CDATA[コマンドプロンプトからキーボード(標準)入力を取得するプログラムです。 肝心の標準入力を取得する手続きはSystem.inフィールドですが、これはバイトストリームでの読み込みを行うメソッドしか持たないので、InputSt &#8230; <a href="http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html">Java: ユーザからの(標準)入力を取得 &#8211; System.inとInputStreamReaderクラス</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドプロンプトからキーボード(標準)入力を取得するプログラムです。</p>
<p>肝心の標準入力を取得する手続きはSystem.inフィールドですが、これはバイトストリームでの読み込みを行うメソッドしか持たないので、InputStreamReaderクラスでラップすることでバイトストリームを文字列に変換出来るメソッドに任せます(read()メソッド)。<br />
しかし、InputStreamReader#read()メソッドは一文字毎にしか読み込めず非効率な面があるので、最後にBufferedReaderクラスでラップすることで入力文字をバッファに格納し一行まとめて読み込めるようにします。(readLine()メソッド)。</p>
<p>このように、高水準のコンポーネントにSystem.inのような低水準のコンポーネントを渡して、その中で低水準メソッドを制御する手法はTemplate Methodパターンに通じるものがあるかも。The Open-Closed Principleですね。</p>
<h3>ソースコード</h3>
<pre>
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ReadLineSample {
  public static void main(String[] args) {
    try {
      BufferedReader stdReader =
        new BufferedReader(new InputStreamReader(System.in));
      System.out.print("INPUT : ");
      String line;
      while ((line = stdReader.readLine()) != null) { // ユーザの一行入力を待つ
        if (line.equals("")) line = "＜空文字＞";
        System.out.print("OUTPUT: " + line);
        System.out.print("\nINPUT : ");
      }
      stdReader.close();
      System.out.println("\nPROGRAM END");
    } catch (Exception e) {
      e.getStackTrace();
      System.exit(-1); // プログラムを終了
    }
  }
}
</pre>
<h3>実行結果</h3>
<p>文字列を入力した後Enterキーを押すと入力した文字がOUTPUTされます。</p>
<pre>
INPUT : Hello World!
OUTPUT: Hello World!
INPUT : こんにちは。
OUTPUT: こんにちは。
INPUT :
OUTPUT: ＜空文字＞
INPUT :
PROGRAM END
</pre>
<p>プログラムを終了する際は、プロンプト上でCtrl+CかCtrl+Zを押してください。それでreadLine()の戻り値はnullとなりwhileループを抜けます。ここでの注意は、単に文字を何も入力せずEnterキーだけ打つと<strong>空文字を返す</strong>ことです（≠null）。</p>
<p>対して、C言語でこういった処理の場合は環境に合わせた改行文字も読み込こんでいます。たぶん、JavaではInputStreamReaderのreadのどこかの段階でその辺は上手く処理されているのかな？気が向いた時に確認してみようかな。<br />
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html" rel="bookmark" title="2008年11月3日">人工無脳を作ってみる (1)入力文の末尾に文字列を追加</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/05/java-intersection.html" rel="bookmark" title="2008年5月20日">検索エンジンを実装 (4)AND演算</a></li>
<li><a href="http://www.yukun.info/blog/2008/01/ruby-string-index.html" rel="bookmark" title="2008年1月5日">Rubyで文字列から日本語文字をインデックス指定する</a></li>
<li><a href="http://www.yukun.info/blog/2008/03/diff-java-ruby-string.html" rel="bookmark" title="2008年3月4日">JavaとRubyで文字列の終端の扱いの違い</a></li>
</ul>
<p><!-- Similar Posts took 9.448 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html">Java: ユーザからの(標準)入力を取得 &#8211; System.inとInputStreamReaderクラス</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/11/java-user-system-in-inputstream-read.html/feed</wfw:commentRss>
		<slash:comments>1</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 20.197 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 8.150 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 7.074 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>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 7.769 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 7.315 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 11.997 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>
		<item>
		<title>Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</title>
		<link>http://www.yukun.info/blog/2008/06/python-csv-read.html</link>
		<comments>http://www.yukun.info/blog/2008/06/python-csv-read.html#comments</comments>
		<pubDate>Mon, 16 Jun 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://www.yukun.info/trump/19700101/python-csv%e3%83%95%e3%82%a1%e3%82%a4%e3%83%ab%e3%81%ae%e8%aa%ad%e3%81%bf%e8%be%bc%e3%81%bf-csvreader%e3%82%aa%e3%83%96%e3%82%b8%e3%82%a7%e3%82%af%e3%83%88%e3%81%ae%e4%bd%bf%e3%81%84%e6%96%b9</guid>
		<description><![CDATA[ソースコード #!/usr/bin/python # coding: UTF-8 # CSVファイルの読み込み import csv filename = "table01.csv" csvfile = open(fil &#8230; <a href="http://www.yukun.info/blog/2008/06/python-csv-read.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

# CSVファイルの読み込み

import csv

filename = "table01.csv"
csvfile = open(filename)
print csvfile

for row in csv.reader(csvfile):
    print row        # 1行のリスト
    for elem in row:
        print elem,    # 行の中の要素
    print

csvfile.close()
print csvfile
</pre>
<h4> CSVファイル (table01.csv) (番号,名前)</h4>
<pre>
1,aki
2,hiro
3,norika
4,kaede
</pre>
<h3> 実行結果</h3>
<pre>
&#60;open file &#39;table01.csv&#39;, mode &#39;r&#39; at 0x01BECCC8&#62;
&#91;&#39;1&#39;, &#39;aki&#39;]
1 aki
&#91;&#39;2&#39;, &#39;hiro&#39;]
2 hiro
&#91;&#39;3&#39;, &#39;norika&#39;]
3 norika
&#91;&#39;4&#39;, &#39;kaede&#39;]
4 kaede
&#60;closed file &#39;table01.csv&#39;, mode &#39;r&#39; at 0x01BECCC8&#62;
</pre>
<h3> リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/module-csv.html" target="_blank">9.1 csv &#8212; CSV File Reading and Writing</a>
<ul>
<li><a href="http://docs.python.org/lib/csv-contents.html" target="_blank">9.1.1 Module Contents</a></li>
<li><a href="http://docs.python.org/lib/csv-examples.html" target="_blank">9.1.5 Examples</a></li>
</ul>
</li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<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/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/08/python-directory-listdir-glob.html" rel="bookmark" title="2008年8月9日">Python: 指定したパスのディレクトリ中のファイル一覧を出力</a></li>
</ul>
<p><!-- Similar Posts took 7.315 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</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/06/python-csv-read.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

