Python saving data values to a csv












0















Now this program reads data from a csv, sums the values per day, and calculates the cumulative values. In the next part, I want it to save the data to a new csv file.



import csv
from collections import defaultdict, OrderedDict


def convert(data):
try:
return int(data)
except ValueError:
return 0


with open('Montdata1.csv', 'r') as file1:
read_file = csv.reader(file1, delimiter=';')
delheader = next(read_file)
data = defaultdict(int)
for line in read_file:
valuedata = max(0, sum([convert(i) for i in line[1:5]]))
data[line[0].split()[0]] += valuedata

for key in OrderedDict(sorted(data.items())):
print('{} {}'.format(key, data[key]))
print("")
previous_values =
for key, value in OrderedDict(sorted(data.items())).items():
print('{} {}'.format(key, value + sum(previous_values)))
previous_values.append(value)


It should be that in the column is the date, and in the second is the values. So it would be something like this:
Example picture



I have tried the following code, but it doesn't do anything:



with open('Datasave.csv', 'w', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimeter= ' ')
for row in spamreader:
print(', '.join(row))


Hope for some help

The data file as csv: https://files.fm/u/2vjppmgv

Data file in pastebin https://pastebin.com/Tw4aYdPc










share|improve this question





























    0















    Now this program reads data from a csv, sums the values per day, and calculates the cumulative values. In the next part, I want it to save the data to a new csv file.



    import csv
    from collections import defaultdict, OrderedDict


    def convert(data):
    try:
    return int(data)
    except ValueError:
    return 0


    with open('Montdata1.csv', 'r') as file1:
    read_file = csv.reader(file1, delimiter=';')
    delheader = next(read_file)
    data = defaultdict(int)
    for line in read_file:
    valuedata = max(0, sum([convert(i) for i in line[1:5]]))
    data[line[0].split()[0]] += valuedata

    for key in OrderedDict(sorted(data.items())):
    print('{} {}'.format(key, data[key]))
    print("")
    previous_values =
    for key, value in OrderedDict(sorted(data.items())).items():
    print('{} {}'.format(key, value + sum(previous_values)))
    previous_values.append(value)


    It should be that in the column is the date, and in the second is the values. So it would be something like this:
    Example picture



    I have tried the following code, but it doesn't do anything:



    with open('Datasave.csv', 'w', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimeter= ' ')
    for row in spamreader:
    print(', '.join(row))


    Hope for some help

    The data file as csv: https://files.fm/u/2vjppmgv

    Data file in pastebin https://pastebin.com/Tw4aYdPc










    share|improve this question



























      0












      0








      0








      Now this program reads data from a csv, sums the values per day, and calculates the cumulative values. In the next part, I want it to save the data to a new csv file.



      import csv
      from collections import defaultdict, OrderedDict


      def convert(data):
      try:
      return int(data)
      except ValueError:
      return 0


      with open('Montdata1.csv', 'r') as file1:
      read_file = csv.reader(file1, delimiter=';')
      delheader = next(read_file)
      data = defaultdict(int)
      for line in read_file:
      valuedata = max(0, sum([convert(i) for i in line[1:5]]))
      data[line[0].split()[0]] += valuedata

      for key in OrderedDict(sorted(data.items())):
      print('{} {}'.format(key, data[key]))
      print("")
      previous_values =
      for key, value in OrderedDict(sorted(data.items())).items():
      print('{} {}'.format(key, value + sum(previous_values)))
      previous_values.append(value)


      It should be that in the column is the date, and in the second is the values. So it would be something like this:
      Example picture



      I have tried the following code, but it doesn't do anything:



      with open('Datasave.csv', 'w', newline='') as csvfile:
      spamreader = csv.reader(csvfile, delimeter= ' ')
      for row in spamreader:
      print(', '.join(row))


      Hope for some help

      The data file as csv: https://files.fm/u/2vjppmgv

      Data file in pastebin https://pastebin.com/Tw4aYdPc










      share|improve this question
















      Now this program reads data from a csv, sums the values per day, and calculates the cumulative values. In the next part, I want it to save the data to a new csv file.



      import csv
      from collections import defaultdict, OrderedDict


      def convert(data):
      try:
      return int(data)
      except ValueError:
      return 0


      with open('Montdata1.csv', 'r') as file1:
      read_file = csv.reader(file1, delimiter=';')
      delheader = next(read_file)
      data = defaultdict(int)
      for line in read_file:
      valuedata = max(0, sum([convert(i) for i in line[1:5]]))
      data[line[0].split()[0]] += valuedata

      for key in OrderedDict(sorted(data.items())):
      print('{} {}'.format(key, data[key]))
      print("")
      previous_values =
      for key, value in OrderedDict(sorted(data.items())).items():
      print('{} {}'.format(key, value + sum(previous_values)))
      previous_values.append(value)


      It should be that in the column is the date, and in the second is the values. So it would be something like this:
      Example picture



      I have tried the following code, but it doesn't do anything:



      with open('Datasave.csv', 'w', newline='') as csvfile:
      spamreader = csv.reader(csvfile, delimeter= ' ')
      for row in spamreader:
      print(', '.join(row))


      Hope for some help

      The data file as csv: https://files.fm/u/2vjppmgv

      Data file in pastebin https://pastebin.com/Tw4aYdPc







      python python-3.x csv save






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 14:18







      Armeija

















      asked Nov 21 '18 at 13:43









      ArmeijaArmeija

      285




      285
























          1 Answer
          1






          active

          oldest

          votes


















          1














          If you just want to use your original code and write to a csv file, you can see how I did it below:



          with open('Datasave.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for item in data:
          writer.writerow([item] + [data[item]])


          With pandas:



          #!/bin/python

          import pandas as pd

          df = pd.read_csv('data.csv', sep=';')

          df['Sum'] = df[df.columns[2:]].sum(axis=1)
          new_df = df.groupby('Time').sum()

          new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0


          With standard libraries:



          import csv

          dates={}

          with open('data.csv', 'r') as df:
          df.readline()
          f = csv.reader(df, delimiter=';')
          for line in f:
          if line[0] not in dates:
          dates[line[0]] = sum(map(int, line[2:]))
          else:
          dates[line[0]] += sum(map(int, line[2:]))

          with open('new_data.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for date in dates:
          writer.writerow([date] + [dates[date]])


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0





          share|improve this answer


























          • Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

            – Armeija
            Nov 21 '18 at 14:17













          • @Armeija sure, see my edits

            – Conner
            Nov 21 '18 at 14:36











          • I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

            – Armeija
            Nov 21 '18 at 14:58













          • Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

            – Armeija
            Nov 21 '18 at 15:01











          • Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

            – Conner
            Nov 21 '18 at 15:19











          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%2f53413434%2fpython-saving-data-values-to-a-csv%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          If you just want to use your original code and write to a csv file, you can see how I did it below:



          with open('Datasave.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for item in data:
          writer.writerow([item] + [data[item]])


          With pandas:



          #!/bin/python

          import pandas as pd

          df = pd.read_csv('data.csv', sep=';')

          df['Sum'] = df[df.columns[2:]].sum(axis=1)
          new_df = df.groupby('Time').sum()

          new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0


          With standard libraries:



          import csv

          dates={}

          with open('data.csv', 'r') as df:
          df.readline()
          f = csv.reader(df, delimiter=';')
          for line in f:
          if line[0] not in dates:
          dates[line[0]] = sum(map(int, line[2:]))
          else:
          dates[line[0]] += sum(map(int, line[2:]))

          with open('new_data.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for date in dates:
          writer.writerow([date] + [dates[date]])


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0





          share|improve this answer


























          • Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

            – Armeija
            Nov 21 '18 at 14:17













          • @Armeija sure, see my edits

            – Conner
            Nov 21 '18 at 14:36











          • I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

            – Armeija
            Nov 21 '18 at 14:58













          • Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

            – Armeija
            Nov 21 '18 at 15:01











          • Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

            – Conner
            Nov 21 '18 at 15:19
















          1














          If you just want to use your original code and write to a csv file, you can see how I did it below:



          with open('Datasave.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for item in data:
          writer.writerow([item] + [data[item]])


          With pandas:



          #!/bin/python

          import pandas as pd

          df = pd.read_csv('data.csv', sep=';')

          df['Sum'] = df[df.columns[2:]].sum(axis=1)
          new_df = df.groupby('Time').sum()

          new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0


          With standard libraries:



          import csv

          dates={}

          with open('data.csv', 'r') as df:
          df.readline()
          f = csv.reader(df, delimiter=';')
          for line in f:
          if line[0] not in dates:
          dates[line[0]] = sum(map(int, line[2:]))
          else:
          dates[line[0]] += sum(map(int, line[2:]))

          with open('new_data.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for date in dates:
          writer.writerow([date] + [dates[date]])


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0





          share|improve this answer


























          • Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

            – Armeija
            Nov 21 '18 at 14:17













          • @Armeija sure, see my edits

            – Conner
            Nov 21 '18 at 14:36











          • I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

            – Armeija
            Nov 21 '18 at 14:58













          • Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

            – Armeija
            Nov 21 '18 at 15:01











          • Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

            – Conner
            Nov 21 '18 at 15:19














          1












          1








          1







          If you just want to use your original code and write to a csv file, you can see how I did it below:



          with open('Datasave.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for item in data:
          writer.writerow([item] + [data[item]])


          With pandas:



          #!/bin/python

          import pandas as pd

          df = pd.read_csv('data.csv', sep=';')

          df['Sum'] = df[df.columns[2:]].sum(axis=1)
          new_df = df.groupby('Time').sum()

          new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0


          With standard libraries:



          import csv

          dates={}

          with open('data.csv', 'r') as df:
          df.readline()
          f = csv.reader(df, delimiter=';')
          for line in f:
          if line[0] not in dates:
          dates[line[0]] = sum(map(int, line[2:]))
          else:
          dates[line[0]] += sum(map(int, line[2:]))

          with open('new_data.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for date in dates:
          writer.writerow([date] + [dates[date]])


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0





          share|improve this answer















          If you just want to use your original code and write to a csv file, you can see how I did it below:



          with open('Datasave.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for item in data:
          writer.writerow([item] + [data[item]])


          With pandas:



          #!/bin/python

          import pandas as pd

          df = pd.read_csv('data.csv', sep=';')

          df['Sum'] = df[df.columns[2:]].sum(axis=1)
          new_df = df.groupby('Time').sum()

          new_df['Sum'].to_frame().to_csv('new_data.csv', sep=';')


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0


          With standard libraries:



          import csv

          dates={}

          with open('data.csv', 'r') as df:
          df.readline()
          f = csv.reader(df, delimiter=';')
          for line in f:
          if line[0] not in dates:
          dates[line[0]] = sum(map(int, line[2:]))
          else:
          dates[line[0]] += sum(map(int, line[2:]))

          with open('new_data.csv', 'w') as df:
          writer = csv.writer(df, delimiter=';', lineterminator='n')
          for date in dates:
          writer.writerow([date] + [dates[date]])


          Output:



          Time;Sum
          1.1.2016;351087.0
          2.1.2016;-2453.0
          3.1.2016;0.0






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 15:18

























          answered Nov 21 '18 at 14:05









          ConnerConner

          23.5k84568




          23.5k84568













          • Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

            – Armeija
            Nov 21 '18 at 14:17













          • @Armeija sure, see my edits

            – Conner
            Nov 21 '18 at 14:36











          • I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

            – Armeija
            Nov 21 '18 at 14:58













          • Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

            – Armeija
            Nov 21 '18 at 15:01











          • Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

            – Conner
            Nov 21 '18 at 15:19



















          • Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

            – Armeija
            Nov 21 '18 at 14:17













          • @Armeija sure, see my edits

            – Conner
            Nov 21 '18 at 14:36











          • I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

            – Armeija
            Nov 21 '18 at 14:58













          • Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

            – Armeija
            Nov 21 '18 at 15:01











          • Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

            – Conner
            Nov 21 '18 at 15:19

















          Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

          – Armeija
          Nov 21 '18 at 14:17







          Is it possible without pandas? I have tried to make this version with default libraries. Also edited the wrong data files

          – Armeija
          Nov 21 '18 at 14:17















          @Armeija sure, see my edits

          – Conner
          Nov 21 '18 at 14:36





          @Armeija sure, see my edits

          – Conner
          Nov 21 '18 at 14:36













          I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

          – Armeija
          Nov 21 '18 at 14:58







          I updated the data file, the first one was the actual file I'm working with, but the current is for the code. Hopefully it doesn't matter too much. If you check my original code with the updated file, you see what the program prints, I was wanting the prints to go to a new file

          – Armeija
          Nov 21 '18 at 14:58















          Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

          – Armeija
          Nov 21 '18 at 15:01





          Sorry for bad explanation; but I meant that the original code prints and does everything right, but I only want it to save the printed data to a new csv file. If this is possible, I'd massivly appreciate it

          – Armeija
          Nov 21 '18 at 15:01













          Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

          – Conner
          Nov 21 '18 at 15:19





          Assuming you're storing things in the data dict... I modified my code writing to csv to use that variable instead.

          – Conner
          Nov 21 '18 at 15:19




















          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%2f53413434%2fpython-saving-data-values-to-a-csv%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







          這個網誌中的熱門文章

          Hercules Kyvelos

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud