Simple file additions and deletions in Python

Source: Internet
Author: User

Fast one months of wood has been updated, in this period of time, the blogger in addition to busy work, has been studying Python programming, according to the circle of friends chatting, Python should be the future of a dragon siege lions in addition to the shell of the necessary Linux scripting language, so to bite the bullet, According to the old boy's Python video lectures, put their own research results posted, has not finished learning, look forward to the old boy's lectures more power.

Ps:1. The old boy's Python video lecture is good, hoping to continue for free ...

2. Bo main programming is rotten, there are some problems, but also please advise ...

3. Recently bought this Python core programming, gnawing book ing ...

System environment: Ubuntu 12.10 Server 64-bit

Python:python 2.7.3

# mkdir Python

# VI Contact_list.txt

-------------------------

1 Zhangsan IT 0001

2 Lisi IT 0002

3 Wangwu HR 0003

4 Zhaoliu OP 0004

-------------------------

# VI staff_list.py

----------------------------------------------------

#!/usr/bin/env python
#encoding: Utf-8 # support Chinese input
Import Sys
Import Getpass
Import Shutil
Import commands
Import time
Import Fileinput
staff_list = ' Contact_list.txt '
# parameter Configuration
user = ' admin '
passwd = ' 123456 '
s = File (staff_list)
SS = S.readlines ()
A = File (Staff_list, ' a ')
Counter = 0
_counter = 0
# Certified Login
While True:
# counter, force exit over 3 times
If Counter <= 3:
# NULL User name judgment
Name = Raw_input ("Please input your name:"). Strip ()
If len (name) = = 0:
Print "Empty Name,try again!"
Continue
# username Password to judge, password hide
# pwd = raw_input ("Please input your password:")
PWD = getpass.getpass (' Please input your password: ')
if pwd = = passwd and name = = User:
Print "Welcome to login,%s"%name
Else
print "Name or password is not valid,please try again!"
Counter +=1
Continue
Break
Else
Print "exceeded 3 times user login. Exit the script
Sys.exit ()
# Select, delete, change, check
While True:
item = raw_input (' "\033[36;1mwelcome to login%s), what do your want to do?
-----------------------
Press ' P ' for print
Press ' a ' for add
Press ' d ' for delete
Press ' U ' for update
Press ' s ' for select
Press ' Q ' for quit
-----------------------
Please make your choise: \033[0m '% ' user)
# Print All
If item = = ' P ':
While True:
User_select = open (staff_list, ' R ')
S_ = User_select.read ()
print '
print ' \033[32;1mthe content of the file\033[0m '
print ' \033[32;1m--------------------------\033[0m '
Print S_
print ' \033[32;1m--------------------------\033[0m '
print '
Break
# Increase
elif item = = ' A ':
While True:
User_add_num = Raw_input (("\033[32;1mplease Input your Number: \033[0m"). Strip ())
User_add_name = Raw_input (("\033[32;1mplease Input your Name: \033[0m"). Strip ())
User_add_dept = Raw_input (("\033[32;1mplease input your department: \033[0m"). Strip ())
user_add_id = Raw_input (("\033[32;1mplease input your ID: \033[0m"). Strip ())
User_item = '%s\t%s\t%s\t%s '% (user_add_num,user_add_name,user_add_dept,user_add_id)
A.write ("\n%s"%user_item)
A.flush ()
Print "\033[32;1madd item:\033[0m"
Print "\033[32;1m------------------\033[0m"
Print User_item
Print "\033[32;1m------------------\033[0m"
Print "\033[32;1madded successful!\033[0m"
# Delete blank Lines
del_blank_in = open (' Contact_list.txt ', ' R ')
del_blank_out = open (' Contact_list_new.txt ', ' W ')
lines = Del_blank_in.readlines ()
For blank in lines:
If Blank.split ():
Del_blank_out.writelines (blank)
Del_blank_in.close ()
Del_blank_out.close ()
# Overwrite Original file
Shutil.move (' Contact_list_new.txt ', ' contact_list.txt ')
User_add_choise = Raw_input (' Press Q for quit or press any key to continue: ')
if user_add_choise = = ' Q ':
print ' bye! '
Break
# Delete
elif item = = ' d ':
While True:
User_del_input = raw_input ("Please input sth to delete:"). Strip ()
If Len (user_del_input) = = 0:
Print "Empty Input,try again!"
Else
# The input value is compared with the source file, then discarded, not added to the new file, the last new file overwrites the source file, implements the deletion function
With open (' Contact_list.txt ', ' R ') as FF:
With open (' Contact_list.txt.new ', ' W ') as GG:
For line in Ff.readlines ():
If User_del_input not in line:
Gg.write (line)
If user_del_input in:
Print "\033[32;1mdelete item:\033[0m"
Print "\033[32;1m------------------\033[0m"
print '%s '%line
_counter + = 1 # counter, to determine the number of hits of the input value
Print "\033[32;1m------------------\033[0m"
Print "\033[32;1mdeleted successful!\033[0m"
If _counter = 0:
print ' Nothing delete! '
Shutil.move (' contact_list.txt.new ', ' contact_list.txt ')
# exit Delete
User_del_input_quit = Raw_input ("\033[32;1mpress Q for quit or press any key to continue?") \033[0m "). Strip ()
if user_del_input_quit = = ' Q ':
Break
# query
elif item = = ' s ':
While True:
Match_yes = 0
#输入判断, ignore space input, add color
User_select_input = raw_input ("\033[32;1mplease input sth to search:\033[0m"). Strip ()
Contact_file = File (staff_list)
If Len (user_select_input) = = 0:
Print "Empty Input,try again!"
Else
While True:
line = Contact_file.readline ()
If Len (line) = = 0:
Break
If user_select_input in:
Match_yes = 1
Print Line
Else
Pass
If Match_yes = 0:
Print "No match item found"
# Exit Query
User_select_input_quit = Raw_input ("\033[32;1mpress Q for quit or press any key to continue?") \033[0m "). Strip ()
if user_select_input_quit = = ' Q ':
Break
# Modify
elif item = = ' U ':
While True:
# input is null and match query content judgment
User_update_input_from = Raw_input ("\033[32;1mplease Search sth to update: \033[0m"). Strip ()
Update_match = 0
Update_file = File (staff_list). ReadLines ()
For N_ in range (len (update_file)):
If User_update_input_from in Update_file[n_]:
Update_match = 1
Else
Pass
If Update_match = 0:
Print "No match item found"
Elif len (user_update_input_from) = = 0:
Print "Empty Input,try again!"
Else
# Modify the matching character to a new character
While True:
user_update_input_to = Raw_input ("\033[32;1mupdate%s to what?\033[0m"% (User_update_input_from)). Strip ()
If Len (user_update_input_to) = = 0:
Print "Empty Input,try again!"
Else
For Line_ in fileinput.input (staff_list,inplace = 1,backup= '. Bak '):
Line_ = Line_.replace (user_update_input_from,user_update_input_to)
Print Line_
# print lines that modify characters
Print "\033[32;1mupdate item:\033[0m"
Output_ = Commands.getoutput ("diff contact_list.txt contact_list.txt.bak|grep ' ^>.* ' | Sed ' s/^>//g ' ")
Print "\033[32;1m---------------------------\033[0m"
Print Output_
Print "\033[32;1m---------------------------\033[0m"
Print "\033[32;1mupdate successfully!\033[0m"
# Delete blank Lines
del_blank_in = open (' Contact_list.txt ', ' R ')
del_blank_out = open (' Contact_list_new.txt ', ' W ')
lines = Del_blank_in.readlines ()
For blank in lines:
If Blank.split ():
Del_blank_out.writelines (blank)
Del_blank_in.close ()
Del_blank_out.close ()
# Overwrite Original file
Shutil.move (' Contact_list_new.txt ', ' contact_list.txt ')
Break
# Exit Update
User_update_input_quit = Raw_input ("\033[32;1mpress Q for quit or press any key to continue?") \033[0m "). Strip ()
if user_update_input_quit = = ' Q ':
Break
# exit
elif item = = ' Q ':
print ' bye! '
Sys.exit ()
Else
Print "\033[31;1mnot a valid key word\033[0m"
Time.sleep (1)

This article comes from "All the Way North" blog, please be sure to keep this source http://showerlee.blog.51cto.com/2047005/1308764

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.