[英]File Modes in Python 2.7
我正在嘗試使數據庫排序,但是我的r +,w +和a +無法正常工作,我必須關閉文件並以不同的方式再次打開以執行每個操作。 這是有效的代碼,但是當我只用一個文件對象和模式將它們寫為r +或w +或rw +或r + w以及r和a的相同組合時,它不會打印。 它只是寫入文件,但不打印行。
import os;
import sys;
def fileInput(numOfEmployees):
for i in range(numOfEmployees):
empId, empFName, empLName, empSalary, empEmailId = raw_input("Enter employee id: "), raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = empId+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fw.write(string);
def fileSearch(searchStr, fr):
line = fr.readline();
while line:
empId, empFName, empLName, empSalary, empEmailId = line.split();
if(searchStr == empFName):
print line;
line = fr.readline();
def main():
numOfEmployees = input("Enter the number of employees: ");
fileInput(numOfEmployees);
fw.close();
searchStr = raw_input("Enter the name of the employee you want to search: ");
fr = open(string, "r");
fileSearch(searchStr, fr);
fr.close();
try:
string = os.path.dirname(os.path.realpath(__file__))+"/FileIO.txt";
fw = open(string, "w");
main();
except KeyboardInterrupt:
fr.close();
fw.close();
sys.exit();
1)如果您使用單個文件句柄(例如fw或fr),請記住在讀取文件時,光標會向下移動文件。 您必須將光標“回滾”到頂部(請參閱seek
)
2)'rw'將覆蓋先前的文件,並從上次運行中刪除先前的條目。 使用“ a +”
嘗試這個:
import os;
import sys;
FileName='FileIO.txt'
def fileInput(fw,numOfEmployees):
for i in range(numOfEmployees):
empId, empFName, empLName, empSalary, empEmailId = raw_input("Enter employee id: "), raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = empId+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fw.write(string);
def fileSearch(fw, searchStr):
line = fw.readline();
while line:
empId, empFName, empLName, empSalary, empEmailId = line.split();
if(searchStr == empFName):
print line;
line = fw.readline();
def main():
string = os.path.dirname(os.path.realpath(__file__))+'/'+FileName;
try:
fw = open(string, "a+");
except KeyboardInterrupt:
sys.exit()
numOfEmployees = input("Enter the number of employees: ");
fileInput(fw,numOfEmployees);
searchStr = raw_input("Enter the name of the employee you want to search: ");
fw.seek(0)
fileSearch(fw,searchStr);
fw.close();
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.