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

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):

主站蜘蛛池模板: 封开县| 灵宝市| 姜堰市| 读书| 临漳县| 本溪市| 富川| 乡城县| 普定县| 周宁县| 红原县| 西乌珠穆沁旗| 沅陵县| 改则县| 凤阳县| 南溪县| 邳州市| 定日县| 宾阳县| 赤城县| 兴安县| 贡山| 宜城市| 罗城| 扎赉特旗| 石嘴山市| 玉林市| 普定县| 庆城县| 黄骅市| 盐山县| 怀仁县| 龙井市| 竹溪县| 绵阳市| 铅山县| 竹山县| 信丰县| 奉贤区| 循化| 黄陵县|