2
$\begingroup$

I want to import txt file with empty line at the end and special characters. I tried many options from the documentation. "String" option detects the empty line but it does not recognise special characters.

file = ParentDirectory@$UserDocumentsDirectory<>"\\Downloads\\nekineki.txt";

Export[file,"123 abc ๐Ÿถ๐Ÿฑ\n"];
SystemOpen@file;

Import@file
Import[file,"String"] 

Out:

enter image description here

What is the right way to import this?

I'm using Mathematica 13.1 and Windows 11.

$\endgroup$
0

2 Answers 2

1
$\begingroup$

It seems that the trailing "\n" is being dropped. I have a verbose workaround.

expStr = ExportString["123 abc ๐Ÿถ๐Ÿฑ\n", "Text"];

Then

StringJoin[
 StringRiffle[
  ImportString[#, "Text"] & /@
   StringSplit[
    ImportString[expStr, "String"]
    , "\n", All]
  , "\n"
  ]
 ]
"123 abc ๐Ÿถ๐Ÿฑ
"

As I said it is verbose; room for improvement.

$\endgroup$
1
  • $\begingroup$ This isn't a workaround for a dropped \n, but rather forces a \n to the end of every read file. Even files that don't have a final \n will receive one here. $\endgroup$
    – Roman
    Sep 20, 2022 at 11:15
2
$\begingroup$

On macOS it works via ReadByteArray and ByteArrayToString:

file = "\\tmp\\nekineki.txt";

Export[file, "123 abc ๐Ÿถ๐Ÿฑ\n"];

ByteArrayToString[ReadByteArray[file]]
(*    "123 abc ๐Ÿถ๐Ÿฑ\n"    *)

We can define a reader function:

myread = ByteArrayToString@*ReadByteArray;

myread[file]
(*    "123 abc ๐Ÿถ๐Ÿฑ\n"    *)

Or, following @GalZoidberg's advice, for Windows we can do

myread = StringDelete["\r"]@*ByteArrayToString@*ReadByteArray;

to make sure we don't end up with lingering \r\n patterns.

$\endgroup$
1
  • 1
    $\begingroup$ This also works. On windows it's just a slight difference, so you do StringDelete[myread[file], "\r"] at the end. $\endgroup$ Sep 20, 2022 at 6:37

Your Answer

By clicking โ€œPost Your Answerโ€, you agree to our terms of service and acknowledge you have read our privacy policy.

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