まず第一に、私はPythonが初めてです。
別の質問と回答Hereがありました。
フォームナマケモノの答えを、私は単一のファイルと単一のオブジェクト処理するコードだ:により、プログラミングの練習の不足にPythonで複数のオブジェクトと複数のファイルを扱うループを追加するには?
import re
# so, we're looking for the object 'HeyThere'
objectname = 'HeyThere'
with open('input.txt', 'r+') as f:
line = f.readline()
pos = f.tell()
found = False
while line:
# we only want to alter the part with the
# right ObjectAlias, so we use the 'found' flag
if 'ObjectAlias ' + objectname in line:
found = True
if 'EndObject' in line:
found = False
if found and 'BeginKeyframe' in line:
# we found the Keyframe part, so we read all lines
# until EndKeyframe and count each line with 'default'
sub_line = f.readline()
frames = 0
while not 'EndKeyframe' in sub_line:
if 'default' in sub_line:
frames += 1
sub_line = f.readline()
# since we want to override the 'BeginKeyframe', we
# have to move back in the file to before this line
f.seek(pos)
# now we read the rest of the file, but we skip the
# old 'BeginKeyframe' line we want to replace
f.readline()
rest = f.read()
# we jump back to the right position again
f.seek(pos)
# and we write our new 'BeginKeyframe' line
f.write(re.sub('\d+', str(frames), line, count=1))
# and write the rest of the file
f.write(rest)
f.truncate()
# nothing to do here anymore, just quit the loop
break
# before reading a new line, we keep track
# of our current position in the file
pos = f.tell()
line = f.readline()
を、私は複数のオブジェクトと、複数のファイルを処理するコードを完了することはできません。
は、このようなもの、私はオブジェクトのリストにObjectNameを変更し、「ラインは一方で」、コードだけでもう動作しない以下のコードを追加しますと言う:申し訳ありませんが、
objectlist = ['GoodMoring', 'GoodAfternoon']
...
while line:
while objectlist:
if 'ObjectAlias ' + objectlist in line:
...
、私はそれは非常に基本的な質問ですけどそれでも、私はまだこの質問をする必要があります:コードを複数のオブジェクトと複数の入力ファイルを処理する方法?
オブジェクトとファイルはどのように関連していますか?すべてのオブジェクトのすべてのファイルを検索する必要がありますか、または各オブジェクトが特定のファイルに対応していますか? – Blckknght
@Blckknght私が今扱っているコードは、** HeyThere ** ** input.txt **で扱うコードです。 ** GoodMoring ** ** GoodAfternoon **などです。 – Tian
whileの代わりにcloseになっています。objectlistのobjectnameに変更してください。 'ObjectAlias' + objectname in line: – Skycc