空の行が最初に出現した後、すべての行を削除したいと思います。
- 空の行に遭遇するまで行を読み進める最良の方法は何ですか?
- 後続のすべての行を削除するための最良のコマンドは何ですか?
使用できるスクリプトを次に示します。メイン関数のコードは、ファイルを選択できるようにするためのものです (または、指定されている場合はコマンド ライン引数として選択します)。次に、crop_file関数を呼び出します。これは、ファイルを開き、最初の空の行までのデータをメモリに読み取り、ファイルを閉じてから、保存したデータを同じファイルに書き込むことで、質問で説明したことを行います。残りの行は削除されました。
コードについて質問がある場合はお知らせください。
#!/usr/bin/python
import os, csv, sys, Tkinter, tkFileDialog as fd
# stop tinker shell from opening as only needed for file dialog
root = Tkinter.Tk()
root.withdraw()
def crop_file(in_path):
# read file into memory
file_obj = open(in_path, 'rb')
reader = csv.reader(file_obj, delimiter='\t')
data = []
for row in reader:
if not row or not any(row):
break #stop at empty row
else:
data.append(row)
file_obj.close()
print 'Found', len(data), 'rows of data without empty lines.'
conf = raw_input('delete remaining lines? (Y|N): ').upper()[0]
if conf == 'Y':
# write data to file
file_obj = open(in_path, 'wb')
writer = csv.writer(file_obj)
writer.writerows(data)
file_obj.close
def main():
in_path = None
prog_name = sys.argv[0]
# check if in_path are inlcuded as cmd line args...
if len(sys.argv) > 1:
in_path = sys.argv[1]
if not os.path.exists(in_path):
print 'Usage:', prog_name, '[file_path>]'
print 'cannot find the file provided for file_path:\n', in_path
sys.exit("Error - invalid excel_file_path arg")
else:
try:
# set current working directory to user's my documents folder
os.chdir(os.path.join(os.getenv('userprofile'),'documents'))
except:
pass
# ask user for path to file...
while not in_path:
print "Please select the file to read data from ..."
try:
in_path = fd.askopenfilename()
except:
print 'Error selecting file.'
if not in_path:
cont = raw_input('Do you want to continue? (Y|N): ').upper()[0]
if cont == 'N':
sys.exit("Error - unable to select input file")
crop_file(in_path)
if __name__ == '__main__':
main()