0

ループ内のコメントが正しいかどうかを把握しようとしています。私が望んでいるように、変数「デバイス」は「リストのリスト」になりますか? その場合、device[0][0] を使用してデータを呼び出すことはできますか? または、3 番目の行と 2 番目の項目が必要な場合は、device[2][1] を使用しますか?

def deviceFile():
    devFile = raw_input('Enter the full file path to your device list file: \n-->')
    open(devFile, 'r')
    device = []
    for line in devFile:
        # creating an array here to hold each line. Call with object[0][0]
        device.append(line.split(','))
    return(device)

編集:

def deviceFile():
'''This def will be used to retrieve a list of devices that will have
commands sent to it via sendCommands(). The user will need to supply
the full file path to the raw_input(). This file will need to be a csv,
will need to have column0 be the IP address, and column1 be the 
hostname(for file naming purposes). If a hostname is not supplied in
column1, the file will be named with the IP address.'''

devFile = raw_input('Enter the full file path to your device list file: \n-->')
thisFile = open(devFile, 'r')
device = []

for line in thisFile:
    # creating an array here to hold each line. Call with object[0][0]
    device.append(line.split(','))
thisFile.close()
return(device)

これは、「自分のコードは完璧か」というよりも、「論理的にこれを行っているか」というタイプの質問です。csvの各行を独自のリストにして、メインプログラムで呼び出すことでアクセスできるようにしたい:

デバイス = deviceFile()

マシン = デバイス[0][0]

最初の行の最初の項目を返します

マシン = デバイス[2][1]

3 行目の 2 番目の項目を返します

4

2 に答える 2

0

あなたの問題は、ファイル オブジェクト (open返されるもの) で何もしていないことですが、代わりに、ファイル オブジェクトであるかのようにファイル名を操作しようとしています。したがって、これを変更するだけです:

devFile = raw_input('Enter the full file path to your device list file: \n-->')
open(devPath, 'r')

これに:

devPath = raw_input('Enter the full file path to your device list file: \n-->')
devFile = open(devPath, 'r')

それを行うと、「機能」しますが、意図した方法ではない可能性があります。たとえば、このファイルの場合:

abc, def
ghi, jkl

あなたはこれを取り戻すでしょう:

[['abc', ' def\n'], ['ghi', ' jkl\n']]

改行文字が保持された行を返す'\n'ため、文字が存在します。for line in devFile:それらを取り除きたい場合は、 などの何かをする必要がありますrstrip('\n')

splitスペースで魔法のようなことを何もしないので、スペースがそこにあります。あなたはそれを分割するように頼みます'abc, def'、そして','あなたは行き​​来します。それらを取り除きたい場合は、結果。'abc'' def'strip

他にもさまざまな小さな問題があります (たとえば、ファイルを閉じないなど) が、コードの動作を実際に停止することはありません。

そう:

def deviceFile():
    devPath = raw_input('Enter the full file path to your device list file: \n-->')
    devFile = open(devPath, 'r')
    device = []
    for line in devFile:
        # creating an array here to hold each line. Call with object[0][0]
        device.append([value.strip() for value in line.rstrip('\n').split(',')])
    return(device)

今、あなたはこれを返します:

[['abc', 'def'], ['ghi', 'jkl']]

それdevice.append([value.strip() for value in line.rstrip('\n').split(',')])はかなり複雑に見えます。rstripできる前に各行を呼び出すsplitことは大したことではありませんが、strip各値を呼び出すリスト内包表記は少し読みにくくなります。また、リスト内包表記が何であるかがわからない場合 (リストに対して明示的なループがあることを考えると、そうなる可能性が高いと思われますappend) device、次のようにする必要があります。

device = []
for line in devFile:
    values = []
    for value in line.rstrip('\n').split(','):
        values.append(value.strip())
    device.append(values)

ただし、これを行うはるかに簡単な方法があります。標準ライブラリのcsvモジュールは、改行や空白などのトリッキーな処理や、まだ考えたことのない処理 (引用符やエスケープ値など) をすべて処理します。

def deviceFile():
    devPath = raw_input('Enter the full file path to your device list file: \n-->')
    with open(devPath) as devFile:
        return list(csv.reader(devFile))
于 2013-03-15T20:44:13.687 に答える
-1

私が間違っている場合は修正してください。ファイルを読み取ってから、ファイル内の各行 (コンマで区切られたもの) を配列に格納しようとしていると思います。たとえば、単に「1、2、3」と書かれたテキスト ファイルがある場合、配列 ['one', 'two', 'three'] を作成しますか? その場合、for ループは必要ありません。単純に次のようにします。

def deviceFile():
    devFile = raw_input('Enter the full file path to your device list file: \n-->')
    myFile = open(devFile, 'r') # Open file in read mode
    readFile = myFile.read() # Read the file

    # Replace enter characters with commas
    readFile = readFile.replace('\n', ',')
    # Split the file by commas, return an array
    return readFile.split(',')

for ループが必要ない理由は、 str.split() が既に配列を返しているからです。実際、「デバイス」を追加する必要さえありません。デバイスはまったく必要ありません。詳細については、文字列のドキュメントを参照してください。

于 2013-03-15T20:14:08.657 に答える