[英]How to read data from multiple text files or an csv file and create output file
I am new to Python.我是 Python 的新手。 My requirement is:我的要求是:
File A (text file): 240 241 and so on文件 A(文本文件):240 241 等
File B (text file): 250 251 and so on文件 B(文本文件):250 251 等
Want to write a script which will take 1 record at a time from each file above and give output as:想要编写一个脚本,该脚本一次从上面的每个文件中获取 1 条记录,并将 output 指定为:
Insert into Table A Where Num1 = 1st record from file A and Num2 = 1st record from file B Update Table A Where Num1 = 1st record from file A and Num2 = 1st record from file B插入表 A 其中 Num1 = 文件 A 中的第一条记录,Num2 = 文件 B 中的第一条记录 更新表 A 其中 Num1 = 文件 A 中的第一条记录,Num2 = 文件 B 中的第一条记录
Insert into Table A Where Num1 = 2nd record from file A and Num2 = 2nd record from file B Update Table A Where Num1 = 2nd record from file A and Num2 = 2nd record from file B插入表 A 其中 Num1 = 文件 A 中的第 2 条记录,Num2 = 文件 B 中的第 2 条记录 更新表 A 其中 Num1 = 文件 A 中的第 2 条记录,Num2 = 文件 B 中的第 2 条记录
Thought of making writing the static (Insert into Table A Where Num1) in file c and use it as below while writing final output file:考虑在 c 文件中编写 static(插入表 A 中的 Num1),并在编写最终 output 文件时按如下方式使用:
for open('output.txt','w') as f: f.write(data from filec + looping data from file A) for open('output.txt','w') as f: f.write(来自 filec 的数据 + 来自文件 A 的循环数据)
Can someone provide solution how can I get outfile data?有人可以提供解决方案如何获取输出数据吗?
if the file is a text file, then you need the open two files and loop on their lines (I don't recommend using with open ("file.txt") as t
when dealing with multiple files at once, so if the records are on separate lines you just need:如果文件是文本文件,那么您需要打开两个文件并在它们的行上循环(我不建议在一次处理多个文件时使用with open ("file.txt") as t
,所以如果记录位于您只需要的单独行上:
file1 = open("file1.txt")
file2 = open("file2.txt")
for lineOf1, lineOf2 in zip(file1, file2):
and here lineOf1
and lineOf2
are the records you need这里lineOf1
和lineOf2
是你需要的记录
and if the records are not on separate lines just add: lineOf1.split("the character separates the records on each line")
and you will have a list of records so you can loop on it again如果记录不在单独的行上,只需添加: lineOf1.split("the character separates the records on each line")
您将拥有一个记录列表,以便您可以再次循环
but if you are dealing with csv I recommend having a look at pandas library.但如果您正在处理 csv,我建议您查看 pandas 库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.