官术网_书友最值得收藏!

Handling files

Once in a while, we need to work on stored data or store some data from a script. For this purpose, we use file-handling techniques.

Consider the example for handling data storage (as a record) :

getinput=input("Do you want to store a new record (Y/N) ")
#this is to remove any extra spaces
getinput=getinput.strip()
#this is to convert all input to lower case
getinput=getinput.lower()
#read values and create a record
if ("y" in getinput):
readvaluename=input("Enter the Name: ")
readvalueage=input("Enter the Age: ")
readvaluelocation=input("Current location: ")
tmpvariable=readvaluename+","+readvalueage+","+readvaluelocation+"\n"
### open a file myrecord.csv in write mode, write the record and close it
fopen=open("myrecord.csv","w")
fopen.write(tmpvariable)
fopen.close()

The output is as follows:

>>
===== RESTART: C:/gdrive/book2/github/edition2/chapter1/file_handling.py =====
Do you want to store a new record (Y/N) n
>>>
===== RESTART: C:/gdrive/book2/github/edition2/chapter1/file_handling.py =====
Do you want to store a new record (Y/N) y
Enter the Name: abhishek
Enter the Age: 10
Current location: US
>>>

Once this is executed, a myrecord.csv file is created in the same location as the script (as we did not specify a file path):

主站蜘蛛池模板: 建阳市| 大新县| 扶风县| 确山县| 宁乡县| 宣威市| 信宜市| 宁都县| 贺兰县| 东阿县| 明光市| 章丘市| 栾城县| 衡南县| 宁乡县| 开平市| 敦化市| 棋牌| 岗巴县| 泰顺县| 松江区| 平果县| 绥德县| 吴堡县| 杭锦旗| 醴陵市| 乐至县| 云阳县| 肇东市| 甘南县| 泗水县| 乐至县| 渝中区| 丹凤县| 靖江市| 吉木乃县| 虞城县| 平武县| 喀喇沁旗| 康定县| 伊吾县|