3 min read•june 24, 2024
and processing are crucial skills for working with data in Python. You'll learn to open, read, and write files, as well as parse CSV data. These techniques are essential for data analysis and manipulation tasks.
Understanding file paths, using the open() function, and working with the are key concepts. You'll also explore reading and writing CSV files, data, and handling different CSV formats. These skills will help you manage and process data effectively in your Python projects.
open(file_path, mode)
file_path
represents the path to the file as a stringmode
specifies how the file should be opened (' for read, ' for write, ' for append)file = open('data.txt', 'r')
opens the file 'data.txt' in read modefile.close()
file.close()
closes the previously opened filewith open(file_path, mode) as file:
with open('data.txt', 'r') as file:
opens the file and automatically closes it after the blockimport csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
value = row[index]
data = [row for row in csv_reader]
stores all rows in a listfiltered_data = [row for row in csv_reader if int(row[1]) > 10]
filters rows based on a conditioncsv_reader = csv.reader(file, [delimiter](https://www.fiveableKeyTerm:Delimiter)=';')
sets the delimiter to a semicolonwith open('output.csv', 'w') as file:
csv_writer = csv.writer(file)
row = [value1, value2, value3]
csv_writer.writerow(row)
rows = [[value1, value2], [value3, value4]]
csv_writer.writerows(rows)
csv_writer = csv.writer(file, delimiter=';')
sets the delimiter to a semicoloncsv_writer = csv.writer(file, quotechar='"')
sets the quote character to double quotescsv_writer = csv.writer(file, lineterminator='\n')
sets the line terminator to a newline character