Luka
Luka

Reputation: 113

Rename files in R

I have problem with renaming files from R.

In my folder on Desktop there are 10 files:

račun 1.xlsx

račun 2.xlsx

...

račun 10.xlsx

I have tried the following:

files <- list.files(path = "myfolder")
file.rename(files,
        paste0("novi_", 1:10, ".xlsx"))

This is what I get as an outcome:

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

I suppose this is because of unicode character č, but I do not know how to find a solution for this.

Upvotes: 3

Views: 4094

Answers (2)

De Novo
De Novo

Reputation: 7610

EDIT 2: The solution here was for the OP to change the Region settings in Control Panel, setting format to be in Serbian(Latin, Serbia).

EDIT 1: See the comments: the OP is on a Windows machine. Here the problem is that list.files() (and presumably dir(), since they call the same .Internal) is converting the non ASCII filenames to ASCII, but Windows is expecting file.exists() to send it the unicode filenames, (and presumably also file.rename())

Try:

file.rename(gsub("c", "č", files), paste0("novi_", seq_along(files, ".xlsx"))
# could work, but it didn't for `file.exists()`

Original answer:

setwd(<your path>)
(files <- list.files())
# [1] "račun 1.xlsx" "račun 2.xlsx" "račun 3.xlsx" "račun 4.xlsx" "račun 5.xlsx [6] "račun 6.xlsx"    
file.rename(files, paste0("novi_", seq_along(files, ".xlsx"))
# [1] TRUE TRUE TRUE TRUE TRUE TRUE

The fact that you specified a path in list.files(), suggests that you're not in the correct directory

Upvotes: 3

Hong Ooi
Hong Ooi

Reputation: 57686

One way to get around this is to use the 8.3 version of a filename, which is guaranteed to be ASCII-only. The main problem is that (as far as I know) there's no way to get this programmatically in R, so you should double-check that this is correct:

files <- paste0("RAUN~", 1:10, ".XLS")
newfiles <- paste0("novi_", 1:10, ".xlsx")
file.rename(files, newfiles)

You can get the 8.3 filenames with DIR /X from the commandline.

Upvotes: 0

Related Questions