Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to import multiple csv file using loop

    So I am having following datasets, and want to import them in a loop, and then save because their name is in sequnce, and for each dataset contain same variables:
    1990 marriage records.csv
    1991 marriage records.csv
    ...
    2018 marriage records.csv

    May I ask what is wrong with following code:
    Code:
    clear all
     
    *change directory to orginal data folder
    cd "..."
    
    for each num of numlist 1990/2017{
    
        import "`num' marriage records.csv"
    
        *change directoty to save data folder
       cd "..."
    
       save nc`num'
       clear
    
    }

  • #2
    Should be:
    Code:
    import delimited "`num' marriage records.csv"
    Also, you will encounter trouble after the first iteration because you don't change back to the import directory. You should either add a cd "..." to return to the original data directory at the start of the loop or reference the file by its full path, as in "C:/.../`num' marriage records.csv" (assuming you use Windows).

    Comment


    • #3
      Originally posted by Ali Atia View Post
      Should be:
      Code:
      import delimited "`num' marriage records.csv"
      Also, you will encounter trouble after the first iteration because you don't change back to the import directory. You should either add a cd "..." to return to the original data directory at the start of the loop or reference the file by its full path, as in "C:/.../`num' marriage records.csv" (assuming you use Windows).
      Thank you, but I am still having trouble with it, the error said
      is not a valid command name.
      Here is my revised code:


      Code:
      clear all
      
      foreach num,of numlist 1990/1995{
          
          clear
      
          
      
          cd "...original..."
          
          
      
          import delimited "`num' marriage records.csv"
      
          
      
          cd"...save..."
          
      
      
      
      
      }

      Comment


      • #4
        Seems like you have some invisible characters in the code which are causing issues (as well as a misplaced comma in your loop). Try copy-pasting this exactly, changing the relevant paths:

        Code:
        clear all
        foreach num of numlist 1990/1995{
            clear
            cd "original"
            import delimited "`num' marriage records.csv"
            cd "save"
            save nc`num'
        }

        Comment

        Working...
        X