將指定文件中的空格或換行刪除(可選是否創建一個新文件)

代碼使用python3寫成,沒有難懂的地方,是個小白代碼,日後會改進,這裏先記錄一下,主要用於16進制導出的文件,其中空格與換行較多,寫個腳本,比較省勁,懶懶懶~~~

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Author:valecalida
import os
import sys
from pathlib import Path

file_input = input("Please input the file_name you want to handle:")

def delete_enter():
	result = ''
	# global_variable()
	f = open(file_input)
	for line in f.readlines():
		line = str(line.replace(' ',''))
		result += line.strip()
	f.close()
	# see_details()

	flag = True
	while flag:
		user_choice = input("If you want to see the details? \nPress 'yes'(y) to see,'no'(n) to ignore.Default:'yes'(y)")
		if user_choice  == 'n':
			while flag:
				choice = input("Do you want to write it into a new file?\nPress 'yes'(y) to see,'no'(n) to ignore.Default:'no'(n) ")
				if choice  == 'y':
					while flag:
						choice1 = input("Just give the new file a name: ")
						# os.system('echo > choice1')
						f1 = open(str(choice1),'w')
						print("Writing into new file...")
						f1.write(str(result))
						f1.close()
						print("Done!")
						flag = False
				else:
					flag = False			
			flag = False
		elif user_choice == 'y' or '\n':
			print(result)
			while flag:
				choice = input("Do you want to write it into a new file?\nPress 'yes'(y) to see,'no'(n) to ignore.Default:'no'(n) ")
				if choice  == 'y':
					while flag:
						choice1 = input("Just give the new file a name: ")
						# os.system('echo > choice1')
						f1 = open(str(choice1),'w')
						print("Writing into new file...")
						f1.write(str(result))
						f1.close()
						print("Done!")
						flag = False
				else:
					flag = False
			flag = False
		else:
			print("Please make sure your input was right!\n")
	#寫入新文件。
	#write into a new file


def detect_file_alive():
	# global_variable()
	# print(file_input)
	path_now = os.getcwd()
	print("Current diretory is :", path_now)
	myfile = Path(str(path_now) + "\\" + str(file_input))
	print("The file you want to operate is :",myfile)
	if myfile.is_file():
		print("The file is exist,you can take next actions!")
	else:
		print("The file does't exist!  Please make sure you were in the right place!")

def start_program():
	# global_variable()
	detect_file_alive()
	delete_enter()
start_program()

代碼重複率比較高,大佬勿噴,小白們可以借鑑一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章