In R I would like to create a text file for each picture I have in a folder and with the same name. By example:

Picture 1.png - Picture 1.txt

Picture 2.png - Picture 2.txt

But the text file name I got is Picture 1.png.txt. How I can avoid to have the image extension in the text name ?

enter image description here

My program is the following

   folder <- "C:/Users/user/Desktop/R/test/" 

   jpeg <- list.files(folder) 

ind <- 0

for (k in jpeg){

  ind <- ind +1

  #Create matrix

  data <- matrix(nrow=1,ncol=5)

  data[1,1:5] <- cbind(a,b,c,d,e)

  filename <- paste(k, ".txt", sep=",")

  write.table(data, filename, row.names = FALSE, col.names = FALSE)

There's lots of functions in base R that do string processing.

For example with:

k = "/somewhere/something/file1.jpg"

you could chop off the last four characters to get the name of the file with no extension:

## [1] "/somewhere/something/file1"

and then use paste to put .txt on it. Or you could substitute .jpg at the end of the path with .txt:

## [1] "file1.txt"

Note the use of \\. to match a real dot (otherwise dot matches any single character) an the use of $ to anchor this match to the end of the path.

Also, this is not really GIS related and probably doesn't belong here, and has probably been well-answered on StackOverflow (and elsewhere many times).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.