I'm pretty new to Python and I'd like to create a script that reads a UTF-8 CSV file containing two columns and writes the output into a UTF-8 strings file. Any help is greatly appreciated.
我是Python的新手,我想创建一个脚本,读取包含两列的UTF-8 CSV文件,并将输出写入UTF-8字符串文件。任何帮助是极大的赞赏。
CSV Example:
KEY,LANGUAGE
keyname1,"Nononono “%{placeholder}”?"
keyname2,"Nononon %{placeholder} nononon."
keyname3,"Open in %{placeholder}?"
keyname4,GB
keyname5,TB
Desired output:
keyname1 = "Nononono “%{placeholder}”?",
keyname2 = "Nononon %{placeholder} nononon.",
keyname3 = "Open in %{placeholder}?",
keyname4 = GB,
keyname5 = TB
So far I was able to read the CSV file and output it to the stdout with the code below:
到目前为止,我能够读取CSV文件并使用以下代码将其输出到stdout:
import csv
def csv_dict_reader(file_obj):
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
print(line["KEY"]),
print(line["LANGUAGE"])
if __name__ == "__main__":
with open("data.csv") as f_obj:
csv_dict_reader(f_obj)
3 个解决方案
#1
You got a good start with the csv
module.
你有一个csv模块的良好开端。
Now you just need to open()
another file in "write" mode for output, and write()
to it.
现在你只需要在“写入”模式下打开()另一个文件进行输出,并向它写入()。
import csv
def csv_dict_reader(file_obj):
"""Read a CSV file with 2 columns and output a new string. """
reader = csv.DictReader(file_obj, delimiter=',')
buf = ""
for line in reader:
buf += line["KEY"] + " = " + line["LANGUAGE"] + "\n"
return buf
if __name__ == "__main__":
with open("test_trans_csv.csv") as f_obj:
with open("test_trans_output.csv", "w") as f_output:
txt = csv_dict_reader(f_obj)
f_output.write(txt)
#2
Why bother with python for something so simple?
为什么这么简单的麻烦?
sed -e 1d -e 's/,/ = /' -e 's/$/,/' data.csv
#3
Change your code to:
将您的代码更改为:
import csv
def csv_dict_reader(file_obj):
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
print("%s = %s"%(line["KEY"],line["LANGUAGE"]))
if __name__ == "__main__":
with open("data.csv") as f_obj:
csv_dict_reader(f_obj)
#1
You got a good start with the csv
module.
你有一个csv模块的良好开端。
Now you just need to open()
another file in "write" mode for output, and write()
to it.
现在你只需要在“写入”模式下打开()另一个文件进行输出,并向它写入()。
import csv
def csv_dict_reader(file_obj):
"""Read a CSV file with 2 columns and output a new string. """
reader = csv.DictReader(file_obj, delimiter=',')
buf = ""
for line in reader:
buf += line["KEY"] + " = " + line["LANGUAGE"] + "\n"
return buf
if __name__ == "__main__":
with open("test_trans_csv.csv") as f_obj:
with open("test_trans_output.csv", "w") as f_output:
txt = csv_dict_reader(f_obj)
f_output.write(txt)
#2
Why bother with python for something so simple?
为什么这么简单的麻烦?
sed -e 1d -e 's/,/ = /' -e 's/$/,/' data.csv
#3
Change your code to:
将您的代码更改为:
import csv
def csv_dict_reader(file_obj):
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
print("%s = %s"%(line["KEY"],line["LANGUAGE"]))
if __name__ == "__main__":
with open("data.csv") as f_obj:
csv_dict_reader(f_obj)