Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

Compare two csv files in python and skip the given row number

I am new to python

I was trying to read csv files and check any difference also to skip the second row of both files

I started something like this

  import sys
  def csv_diff(file_f,file_g):
      #file_f = sys.argv[1]
      #file_g = sys.argv[2]
      set_f = set()
      set_g = set()
      with open(file_f) as f:
          line = f.readline().strip()
          while line:
              set_f.add(line)
              line = f.readline().strip()
      with open(file_g) as g:
          line = g.readline().strip()
          while line:
              set_g.add(line)
              line = g.readline().strip()
      diff = set_f - set_g

      # print set_f
      # print set_g
      # print diff
      if diff:
          #print "Data mismatch between the files"
          return False
      else:
          #print " Data Matches "
          return True

But this code not reading the first line

My csv file

File Name : man.csv
Start Time : 2017-02-17T09:46:50
Read Count : 1
Write Count : 0
Filter Count : 0
Skip Count : 1

I am looking to skip the line: Start Time : 2017-02-17T09:46:50

Any easy and better approach?

question from:https://stackoverflow.com/questions/65831492/compare-two-csv-files-in-python-and-skip-the-given-row-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try the following if your csv has many entries and you want to always skip Start Time. This will also work if your csv as only 1 entry as well.

def csv_diff(file_1, file_2):
    with open(file_1, "r") as f1, open(file_2, "r") as f2:
        for line1, line2 in zip(f1, f2):
            if line1.startswith("Start Time"):
                continue
            if line1.strip() != line2.strip():
                print(f"The two files '{file_1}' and '{file_2}' do not match!")
                return False
    print(f"The two files '{file_1}' and '{file_2}' are a match!")
    return True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...