File Handling
File Handling
Example program:
file1 = open("myfile.txt", "w")
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Write to Text File in Python
There are two ways to write in a file:
∙ Using write()
∙ Using writelines()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
writelines(): For a list of string elements, each string is inserted in the text file.Used
to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
∙ writerows(): This method is used to write multiple rows at a time. This can be used to write
rows list.
Syntax:
writerows(rows)
We can also write dictionary to the CSV file. For this the CSV module provides the csv.DictWriter
class. This class returns a writer object which maps dictionaries onto output rows.
Syntax:
csv.DictWriter(csvfile, fieldnames, restval=”,
extrasaction=’raise’, dialect=’excel’, *args, **kwds)
csv.DictWriter provides two methods for writing to CSV. They are:
∙ writeheader(): writeheader() method simply writes the first row of your csv file using the
pre-specified fieldnames.
Syntax:
writeheader()
∙ writerows(): writerows method simply writes all the rows but in each row, it writes only the
values(not keys).
Syntax:
writerows(mydict)