Converting CSV to Json issue with for loop on CENTOSHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Accessing the index in 'for' loops?Why does Google prepend while(1); to their JSON responses?Iterating over dictionaries using 'for' loopsConvert JS object to JSON stringParse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?

Trying to create a folder with date and time with a space

Does two puncture wounds mean venomous snake?

First amendment and employment: Can an employer terminate you for speech?

What is the idiomatic way of saying “he is ticklish under armpits”?

Are any jet engines used in combat aircraft water cooled?

Word or idiom defining something barely functional

How can glass marbles naturally occur in a desert?

Does the United States guarantee any unique freedoms?

Colors and corresponding numbers

How to use grep to search through the --help output?

Performance of a branch and bound algorithm VS branch-cut-heuristics

Author changing name

Infeasibility in mathematical optimization models

Why are Gatwick's runways too close together?

Can I legally make a real mobile app based on a fictional app from a TV show?

What does "sardine box" mean?

English - Acceptable use of parentheses in an author's name

Was this a rapid SCHEDULED disassembly? How was it done?

Plausibility of Ice Eaters in the Arctic

Can we tile the board by L trominos?

Could one become a successful researcher by writing some really good papers while being outside academia?

Optimal way to extract "positive part" of a multivariate polynomial

Improve survivability of bicycle container

I was asked to prove the Principle of Cauchy Induction



Converting CSV to Json issue with for loop on CENTOS


How do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Accessing the index in 'for' loops?Why does Google prepend while(1); to their JSON responses?Iterating over dictionaries using 'for' loopsConvert JS object to JSON stringParse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I want to convert a csv file to json file, it's work on my computer but not on my centos server



My python version on my computer is python 3.7.2, and the csv is rightly convert to json locally.



So i've tried to update my python on Centos, my current version is python 2.6.6



#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
write_json(csv_rows, json_file, format)


I expect that my function can read my csv file but in place, python return my this error :



csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
^
SyntaxError: invalid syntax


Obviously this error doesn't exist on my computer, only on this CentOS server



Do you think i've must update my python 2 to python 3 ?










share|improve this question


























  • Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

    – Arne
    Mar 27 at 7:40











  • It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

    – Lyazarus
    Mar 27 at 7:44






  • 1





    Remove the extra colon in the end of the csv_rows.extend line

    – Devesh Kumar Singh
    Mar 27 at 7:46











  • It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

    – Arne
    Mar 27 at 7:50











  • Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

    – Lyazarus
    Mar 27 at 7:51

















0















I want to convert a csv file to json file, it's work on my computer but not on my centos server



My python version on my computer is python 3.7.2, and the csv is rightly convert to json locally.



So i've tried to update my python on Centos, my current version is python 2.6.6



#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
write_json(csv_rows, json_file, format)


I expect that my function can read my csv file but in place, python return my this error :



csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
^
SyntaxError: invalid syntax


Obviously this error doesn't exist on my computer, only on this CentOS server



Do you think i've must update my python 2 to python 3 ?










share|improve this question


























  • Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

    – Arne
    Mar 27 at 7:40











  • It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

    – Lyazarus
    Mar 27 at 7:44






  • 1





    Remove the extra colon in the end of the csv_rows.extend line

    – Devesh Kumar Singh
    Mar 27 at 7:46











  • It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

    – Arne
    Mar 27 at 7:50











  • Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

    – Lyazarus
    Mar 27 at 7:51













0












0








0








I want to convert a csv file to json file, it's work on my computer but not on my centos server



My python version on my computer is python 3.7.2, and the csv is rightly convert to json locally.



So i've tried to update my python on Centos, my current version is python 2.6.6



#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
write_json(csv_rows, json_file, format)


I expect that my function can read my csv file but in place, python return my this error :



csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
^
SyntaxError: invalid syntax


Obviously this error doesn't exist on my computer, only on this CentOS server



Do you think i've must update my python 2 to python 3 ?










share|improve this question
















I want to convert a csv file to json file, it's work on my computer but not on my centos server



My python version on my computer is python 3.7.2, and the csv is rightly convert to json locally.



So i've tried to update my python on Centos, my current version is python 2.6.6



#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
write_json(csv_rows, json_file, format)


I expect that my function can read my csv file but in place, python return my this error :



csv_rows.extend([title[i]:row[title[i]] for i in range(len(title))])
^
SyntaxError: invalid syntax


Obviously this error doesn't exist on my computer, only on this CentOS server



Do you think i've must update my python 2 to python 3 ?







python json csv centos






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 8:02







Lyazarus

















asked Mar 27 at 7:37









LyazarusLyazarus

11 bronze badge




11 bronze badge















  • Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

    – Arne
    Mar 27 at 7:40











  • It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

    – Lyazarus
    Mar 27 at 7:44






  • 1





    Remove the extra colon in the end of the csv_rows.extend line

    – Devesh Kumar Singh
    Mar 27 at 7:46











  • It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

    – Arne
    Mar 27 at 7:50











  • Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

    – Lyazarus
    Mar 27 at 7:51

















  • Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

    – Arne
    Mar 27 at 7:40











  • It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

    – Lyazarus
    Mar 27 at 7:44






  • 1





    Remove the extra colon in the end of the csv_rows.extend line

    – Devesh Kumar Singh
    Mar 27 at 7:46











  • It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

    – Arne
    Mar 27 at 7:50











  • Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

    – Lyazarus
    Mar 27 at 7:51
















Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

– Arne
Mar 27 at 7:40





Is that all the code, or just an excerpt? Because getting that code python2 compliant is probably way easier than updating from 2 to 3 on centos.

– Arne
Mar 27 at 7:40













It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

– Lyazarus
Mar 27 at 7:44





It's just a part of my code, your right, upgrade python 2 to python 3 looks difficult for me

– Lyazarus
Mar 27 at 7:44




1




1





Remove the extra colon in the end of the csv_rows.extend line

– Devesh Kumar Singh
Mar 27 at 7:46





Remove the extra colon in the end of the csv_rows.extend line

– Devesh Kumar Singh
Mar 27 at 7:46













It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

– Arne
Mar 27 at 7:50





It mostly depends on whether you have the rights to add epel to the mirror list and install python from there.

– Arne
Mar 27 at 7:50













Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

– Lyazarus
Mar 27 at 7:51





Now the the Syntax error is ont the "row" python csv_rows.extend([title[i]row[title[i]] for i in range(len(title))]) ^ SyntaxError: invalid syntax

– Lyazarus
Mar 27 at 7:51












2 Answers
2






active

oldest

votes


















0














The code below was tested under python 3.6 and 2.7



(I believe this is what you are looking for)



reader = [['1','2','3'],['11','22','33'],['111','222','333']]
csv_rows = []
title = ['T1','T2','T3']
for row in reader:
csv_rows.extend([ title[i]:row[i] for i in range(len(title)) ])

print(csv_rows)


Output



['T2': '2', 'T3': '3', 'T1': '1', 'T2': '22', 'T3': '33', 'T1': '11', 'T2': '222', 'T3': '333', 'T1': '111']





share|improve this answer
































    0














    Little optimization and readability tip: avoid index selection if possible.

    If you are iterating on both the index and the value of an iterable, avoid using range(len(x)), and use directly enumerate, is much faster in python and more readable.



    Improving @balderman's answer:



    reader = [['1','2','3'],['11','22','33'],['111','222','333']]
    csv_rows = []
    title = ['T1','T2','T3']
    for row in reader:
    csv_rows.extend([val: row[idx] for idx, val in enumerate(title)])
    print(csv_rows)


    Even better and clearer is to avoid using indexes at all:



    reader = [['1','2','3'],['11','22','33'],['111','222','333']]
    csv_rows = []
    title = ['T1','T2','T3']
    for row in reader:
    csv_rows.extend([ t_val: r_val for (t_val, r_val) in zip(title, row) ])
    print(csv_rows)


    Even more compact (and faster):



    reader = [['1','2','3'],['11','22','33'],['111','222','333']]
    title = ['T1','T2','T3']

    csv_rows = [t_val: r_val for (t_val, r_val) in zip(title, row) for row in reader]
    print(csv_rows)


    List and dict-comprehensions are a bit tricky at the beginning, but if you think of them as "for loops with the for placed after" they are not so weird.






    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371991%2fconverting-csv-to-json-issue-with-for-loop-on-centos%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      The code below was tested under python 3.6 and 2.7



      (I believe this is what you are looking for)



      reader = [['1','2','3'],['11','22','33'],['111','222','333']]
      csv_rows = []
      title = ['T1','T2','T3']
      for row in reader:
      csv_rows.extend([ title[i]:row[i] for i in range(len(title)) ])

      print(csv_rows)


      Output



      ['T2': '2', 'T3': '3', 'T1': '1', 'T2': '22', 'T3': '33', 'T1': '11', 'T2': '222', 'T3': '333', 'T1': '111']





      share|improve this answer





























        0














        The code below was tested under python 3.6 and 2.7



        (I believe this is what you are looking for)



        reader = [['1','2','3'],['11','22','33'],['111','222','333']]
        csv_rows = []
        title = ['T1','T2','T3']
        for row in reader:
        csv_rows.extend([ title[i]:row[i] for i in range(len(title)) ])

        print(csv_rows)


        Output



        ['T2': '2', 'T3': '3', 'T1': '1', 'T2': '22', 'T3': '33', 'T1': '11', 'T2': '222', 'T3': '333', 'T1': '111']





        share|improve this answer



























          0












          0








          0







          The code below was tested under python 3.6 and 2.7



          (I believe this is what you are looking for)



          reader = [['1','2','3'],['11','22','33'],['111','222','333']]
          csv_rows = []
          title = ['T1','T2','T3']
          for row in reader:
          csv_rows.extend([ title[i]:row[i] for i in range(len(title)) ])

          print(csv_rows)


          Output



          ['T2': '2', 'T3': '3', 'T1': '1', 'T2': '22', 'T3': '33', 'T1': '11', 'T2': '222', 'T3': '333', 'T1': '111']





          share|improve this answer













          The code below was tested under python 3.6 and 2.7



          (I believe this is what you are looking for)



          reader = [['1','2','3'],['11','22','33'],['111','222','333']]
          csv_rows = []
          title = ['T1','T2','T3']
          for row in reader:
          csv_rows.extend([ title[i]:row[i] for i in range(len(title)) ])

          print(csv_rows)


          Output



          ['T2': '2', 'T3': '3', 'T1': '1', 'T2': '22', 'T3': '33', 'T1': '11', 'T2': '222', 'T3': '333', 'T1': '111']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 at 9:04









          baldermanbalderman

          3,5091 gold badge15 silver badges23 bronze badges




          3,5091 gold badge15 silver badges23 bronze badges


























              0














              Little optimization and readability tip: avoid index selection if possible.

              If you are iterating on both the index and the value of an iterable, avoid using range(len(x)), and use directly enumerate, is much faster in python and more readable.



              Improving @balderman's answer:



              reader = [['1','2','3'],['11','22','33'],['111','222','333']]
              csv_rows = []
              title = ['T1','T2','T3']
              for row in reader:
              csv_rows.extend([val: row[idx] for idx, val in enumerate(title)])
              print(csv_rows)


              Even better and clearer is to avoid using indexes at all:



              reader = [['1','2','3'],['11','22','33'],['111','222','333']]
              csv_rows = []
              title = ['T1','T2','T3']
              for row in reader:
              csv_rows.extend([ t_val: r_val for (t_val, r_val) in zip(title, row) ])
              print(csv_rows)


              Even more compact (and faster):



              reader = [['1','2','3'],['11','22','33'],['111','222','333']]
              title = ['T1','T2','T3']

              csv_rows = [t_val: r_val for (t_val, r_val) in zip(title, row) for row in reader]
              print(csv_rows)


              List and dict-comprehensions are a bit tricky at the beginning, but if you think of them as "for loops with the for placed after" they are not so weird.






              share|improve this answer





























                0














                Little optimization and readability tip: avoid index selection if possible.

                If you are iterating on both the index and the value of an iterable, avoid using range(len(x)), and use directly enumerate, is much faster in python and more readable.



                Improving @balderman's answer:



                reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                csv_rows = []
                title = ['T1','T2','T3']
                for row in reader:
                csv_rows.extend([val: row[idx] for idx, val in enumerate(title)])
                print(csv_rows)


                Even better and clearer is to avoid using indexes at all:



                reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                csv_rows = []
                title = ['T1','T2','T3']
                for row in reader:
                csv_rows.extend([ t_val: r_val for (t_val, r_val) in zip(title, row) ])
                print(csv_rows)


                Even more compact (and faster):



                reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                title = ['T1','T2','T3']

                csv_rows = [t_val: r_val for (t_val, r_val) in zip(title, row) for row in reader]
                print(csv_rows)


                List and dict-comprehensions are a bit tricky at the beginning, but if you think of them as "for loops with the for placed after" they are not so weird.






                share|improve this answer



























                  0












                  0








                  0







                  Little optimization and readability tip: avoid index selection if possible.

                  If you are iterating on both the index and the value of an iterable, avoid using range(len(x)), and use directly enumerate, is much faster in python and more readable.



                  Improving @balderman's answer:



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  csv_rows = []
                  title = ['T1','T2','T3']
                  for row in reader:
                  csv_rows.extend([val: row[idx] for idx, val in enumerate(title)])
                  print(csv_rows)


                  Even better and clearer is to avoid using indexes at all:



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  csv_rows = []
                  title = ['T1','T2','T3']
                  for row in reader:
                  csv_rows.extend([ t_val: r_val for (t_val, r_val) in zip(title, row) ])
                  print(csv_rows)


                  Even more compact (and faster):



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  title = ['T1','T2','T3']

                  csv_rows = [t_val: r_val for (t_val, r_val) in zip(title, row) for row in reader]
                  print(csv_rows)


                  List and dict-comprehensions are a bit tricky at the beginning, but if you think of them as "for loops with the for placed after" they are not so weird.






                  share|improve this answer













                  Little optimization and readability tip: avoid index selection if possible.

                  If you are iterating on both the index and the value of an iterable, avoid using range(len(x)), and use directly enumerate, is much faster in python and more readable.



                  Improving @balderman's answer:



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  csv_rows = []
                  title = ['T1','T2','T3']
                  for row in reader:
                  csv_rows.extend([val: row[idx] for idx, val in enumerate(title)])
                  print(csv_rows)


                  Even better and clearer is to avoid using indexes at all:



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  csv_rows = []
                  title = ['T1','T2','T3']
                  for row in reader:
                  csv_rows.extend([ t_val: r_val for (t_val, r_val) in zip(title, row) ])
                  print(csv_rows)


                  Even more compact (and faster):



                  reader = [['1','2','3'],['11','22','33'],['111','222','333']]
                  title = ['T1','T2','T3']

                  csv_rows = [t_val: r_val for (t_val, r_val) in zip(title, row) for row in reader]
                  print(csv_rows)


                  List and dict-comprehensions are a bit tricky at the beginning, but if you think of them as "for loops with the for placed after" they are not so weird.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 11:11









                  Alberto ChiusoleAlberto Chiusole

                  4394 silver badges16 bronze badges




                  4394 silver badges16 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371991%2fconverting-csv-to-json-issue-with-for-loop-on-centos%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해