質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

1281閲覧

text file editing

xRein

総合スコア6

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2018/07/06 05:32

編集2018/07/06 06:27

python3 を使ってテキストfileの中の特定の1行だけを指定して消去することは可能でしょうか? できる限りパッケージなどを使わないでできる方法があれば教えていただきたいです。また、自分が書いたコードに改善点があればよければ教えてください。

python3

1def createfile(): 2 file_name = str(input('Enter the file name: ')) 3 try: 4 score_file = open(file_name + '.txt', 'w') 5 score_file.close() 6 except: 7 print('An error occured at creating.') 8 else: 9 print(file_name + '.txt is created') 10 11def searchfile(): 12 file_name = str(input('Enter the file name which you want to see.: ')) 13 try: 14 score_file = open(file_name, 'r') 15 name = score_file.readline() 16 while name != '': 17 score = score_file.readline() 18 name = name.rstrip('\n') 19 score = score.rstrip('\n') 20 print(name, score) 21 name = score_file.readline() 22 except: 23 print('An error occured at adding.') 24 25def addfile(): 26 try: 27 file_name = str(input('Enter the file name which you want to add to.: ')) 28 add = '1' 29 while add == '1': 30 name = str(input('Enter a student name: ')) 31 score = str(input('Enter his/her score: ')) 32 score_file = open(file_name, 'a') 33 score_file.write('Name:'+ name + '\n') 34 score_file.write('Score:' + score + '\n') 35 score_file.close() 36 add = input('If you want to continue adding new data, press 1: ') 37 except(): 38 print('An error occured at adding.') 39 40def main(): 41 kc = 'y' 42 while kc == 'y': 43 press = input('Press 1 to create a new course score file.\nPress 2 to search into an existing course score file.\nPress 3 to add more scores to an existing course score file.: ') 44 if press == '1': 45 createfile() 46 elif press == '2': 47 searchfile() 48 elif press == '3': 49 addfile() 50 51 kc = input('If you continue process press y: ') 52 print ('Good Bye!') 53 54main()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

umyu

2018/07/06 05:44

プログラムのソースコードはcodeタグで囲ってくださいな。
xRein

2018/07/06 06:27

ありがとうございます。不慣れで申し訳ないです。
guest

回答2

0

まず、全部の行を読み込み、特定の行をそこから削除し、改めて書き込む、という操作となりますね

投稿2018/07/06 05:37

y_waiwai

総合スコア87719

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

Python

1# -*- coding: utf-8 -*- 2 3def createfile(): 4 file_name = str(input('Enter the file name: ')) 5 try: 6 with open(file_name + '.txt', 'w', encoding='utf-8') as score_file: 7 pass 8 except: 9 print('An error occured at creating.') 10 else: 11 print(file_name + '.txt is created') 12 13 14def searchfile(): 15 file_name = str(input('Enter the file name which you want to see.: ')) 16 try: 17 with open(file_name, 'r', encoding='utf-8') as score_file: 18 19 name = score_file.readline() 20 while name != '': 21 score = score_file.readline() 22 name = name.rstrip('\n') 23 score = score.rstrip('\n') 24 print(name, score) 25 name = score_file.readline() 26 except: 27 print('An error occured at adding.') 28 29 30def addfile(): 31 try: 32 file_name = str(input('Enter the file name which you want to add to.: ')) 33 add = '1' 34 while add == '1': 35 name = str(input('Enter a student name: ')) 36 score = str(input('Enter his/her score: ')) 37 with open(file_name, 'a', encoding='utf-8') as score_file: 38 score_file.write('Name:' + name + '\n') 39 score_file.write('Score:' + score + '\n') 40 add = input('If you want to continue adding new data, press 1: ') 41 except(): 42 print('An error occured at adding.') 43 44def deleteline(): 45 file_name = str(input('Enter the file name which you want to see.: ')) 46 with open(file_name, 'r', encoding='utf-8') as score_file: 47 lines = score_file.readlines() 48 line_n = int(input('Delete line.: ')) 49 with open(file_name, 'w', encoding='utf-8') as score_file: 50 for i, line in enumerate(lines, start=1): 51 if i == line_n: 52 continue 53 score_file.write(line) 54 55def main(): 56 PROCESSING = {"1": createfile, "2": searchfile, "3": addfile, "4": deleteline} 57 kc = 'y' 58 while kc == 'y': 59 msg = """Press 1 to create a new course score file. 60Press 2 to search into an existing course score file. 61Press 3 to add more scores to an existing course score file.: 62Press 4 to delete line: """ 63 press = input(msg) 64 command = PROCESSING.get(press) 65 if command is not None: 66 command() 67 kc = input('If you continue process press y: ') 68 print ('Good Bye!') 69 70 71if __name__ == "__main__": 72 main() 73

その他改造点
0. 例外発生時にもcloseが実行されるように、with文を使用。
0. ファイルを読み書きするときは、環境依存を避けるためにencoding形式を明示的に指定。
0. PROCESSING のdictでファイル作成/検索/追記を管理

ファイルで管理するなら、csvモジュールまたはjsonモジュール
頻繁に内容を書き換えるなら、sqliteで管理してもいいかと。


◇余談
以下の書き込み部分でもしも書き込み途中に何らかの障害(PCの電源断,アプリが落とされた,etc)が発生した時にファイルの元データがロストしてしまいます。

Python

1 with open(file_name, 'w', encoding='utf-8') as score_file: 2 for i, line in enumerate(lines, start=1): 3 if i == line_n: 4 continue 5 score_file.write(line)

ファイルが不整合な状態を防ぐにはトランザクション機能があるsqliteなどのデータベースで管理するが一番良いのですが、
別ファイル(tempfile — 一時ファイルやディレクトリの作成)に書き込み、最後にos.replaceで元ファイルにコピーしてくださいな。
これで削除処理はロストしますが、ファイルデータのロストはしないです。

投稿2018/07/07 17:45

編集2018/07/08 05:14
umyu

総合スコア5846

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問