PYTHON file manipulation creation, deletion, modification processing

Source: Internet
Author: User

In peacetime, some of the system files or directory of the increase in the search, which requires the use of some Python libraries, such as the OS, etc.


To manipulate a file

First you introduce the OS

Import OS

Reading and writing a file requires opening this file

You can use open (Dir,type) to manipulate, open a file, or write a file in the directory if the path in Windows requires

"\" Double slash-delimited, or you can use R to keep the directory original path R ' C:/test.txt ' in the string

File = Open ("C:\test.txt", "w+") #打开并对文件进行写操作

File = Open ("C:\test.txt", "R") #打开并对文件进行读操作

Delete a file can be Os.remove (dir,)

If the file is read-only you need to do some other action

Introduction of Stat

Import Stat,os

Os.chmod (filename, stat. S_iwrite)

Operate on a directory (folder)

Lists the files in the specified directory

Import OS

for filename in Os.listdir (dir)

#操作

Judge whether a string is a directory

Using Os.isdir (dir)

Traversing a directory of files can be used walk

For Root,dirs,files in Os.walk (RootDir)

#


Delete a folder (there can be files inside) to use:

The first one is to include a shutil

Import Shutil

Shutil.rmtree (PATH)

Some of the above basic file processing, I would like to introduce a friend write file creation, delete, modify the processing class.

#!/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 (' "33[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:33[0m '% user '

# Print All
If item = = ' P ':
While True:
User_select = open (staff_list, ' R ')
S_ = User_select.read ()
print '
print ' 33[32;1mthe content of the file33[0m '
print ' 33[32;1m--------------------------33[0m '
Print S_
print ' 33[32;1m--------------------------33[0m '
print '
Break

# Increase
elif item = = ' A ':
While True:
User_add_num = Raw_input (("33[32;1mplease input your number:33[0m"). Strip ())
User_add_name = Raw_input (("33[32;1mplease input your name:33[0m"). Strip ())
User_add_dept = raw_input ("33[32;1mplease input your department:33[0m"). Strip

())
user_add_id = Raw_input (("33[32;1mplease input your id:33[0m"). Strip ())
User_item = '%st%st%st%s '% (user_add_num,user_add_name,user_add_dept,user_add_id)
A.write ("n%s"%user_item)
A.flush ()
Print "33[32;1madd item:33[0m"
Print "33[32;1m------------------33[0m"
Print User_item
Print "33[32;1m------------------33[0m"
Print "33[32;1madded successful!33[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 "33[32;1mdelete item:33[0m"
Print "33[32;1m------------------33[0m"
print '%s '%line
_counter + = 1 # counter, to determine the number of hits of the input value
Print "33[32;1m------------------33[0m"
Print "33[32;1mdeleted successful!33[0m"
If _counter = 0:
print ' Nothing delete! '
Shutil.move (' contact_list.txt.new ', ' contact_list.txt ')
# exit Delete
User_del_input_quit = Raw_input ("33[32;1mpress Q for quit or press any key to"

Continue? 33[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 ("33[32;1mplease input sth to search:33[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 ("33[32;1mpress Q for quit or press any key to"

Continue? 33[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 ("33[32;1mplease search sth to Update:33

[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:
  & nbsp;  Pass
      If Update_match = 0:
        Print "No match item found"
      elif len (user_update_input_from) = 0:
  & nbsp;     print "Empty Input,try again!"
      Else:
 # modifies the matching character to the new character
 while True:
     User_ update_input_to = Raw_input ("33[32;1mupdate%s to what?33[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 "33[32;1mupdate item:33[0m"
Output_ = Commands.getoutput ("diff Contact_list.txt Contact_list.txt.bak|grep

' ^>.* ' | Sed ' s/^>//g ' ")
Print "33[32;1m---------------------------33[0m"
Print Output_
Print "33[32;1m---------------------------33[0m"
Print "33[32;1mupdate successfully!33[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 ("33[32;1mpress Q for quit or press any key to"

Continue 33[0m "). Strip ()
        if user_update_input_quit = = ' Q ':
     break   
 
      
  # exit
  elif Item = = ' Q ':
    print ' bye! '
    sys.exit ()
 
  else:
    print "33[31;1mnot a valid key word 33[0m "
    time.sleep (1)

Related Article

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.