--I want to convert the delimiter of the csv file to tab delimiter. --If the file contains commas such as addresses, it is easier to perform subsequent processing (for example, importing into DB) by separating them into tabs.
~~-Easy to import and use csv module ~~ ~~ Import the csv module in the calling program ~~
--Import csv module at the beginning of def file
--Read and write the target file with open
--Read the target files separated by commas and export them separated by tabs
→ Overwritten on the target file
--After reading using csv.reader
, store it in an array row by row
--For writing, write the array read in ↑ with `writer.writer rows (array name)`
at once.
If you want to write line by line, you can write with `writer.writerrow (matrix)`
convertTav.py
def CsvToTsv(path):
#Array for reading
line = []
#Read
with open(path, "r", newline="") as f:
#Create read object (comma separated)
reader = csv.reader(f, delimiter = ",")
#Read
line = [row for row in reader]
#close
f.close
#writing
with open(path, "w", newline="") as f:
#Create write object (tab delimited)
writer = csv.writer(f, delimiter = "\t")
#Write all together
writer.writerows(line)
#close
f.close
If you want to convert encode by reading and writing, specify encoding at open (Example) Shift-jis when reading, utf-8 when writing
convertTav.py
#Read
with open(path, "r", newline="", encoding="cp932") as f:
#writing
with open(path, "w", newline="", encoding="utf_8") as f:
** It didn't work with Shift-jis, it worked with cp932 **
Recommended Posts