Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I would like to know if it's safe to do batch operations in a list of package files, applying a function like this:

SetAttributes[packStringReplace,HoldRest]
packStringReplace[packPath_String,{replaceRule__}]:=Module[{pack},
    pack=Import[packPath,"Text"];
    pack=StringReplace[pack,{replaceRule}];
    Export[packPath,pack,"Text"]
]

packs=FileNames["*.m","/packageDirectory",∞];
packStringReplace[#,{"text1"->"text2","text3"->"text4"}]&/@packs

Can Import and Export change something inside pack in some unexpected way? It's safe? Or should I use ImportString or another Import equivalent? If yes, why?

Update

As pointed by @AlbertRetey in the comments, it's safer do use:

Export[packname,pack,"Text",CharacterEncoding->"ASCII"]

instead of

Export[packPath,pack,"Text"]

share|improve this question
    
I don't know of any voodoo for the "Text" format, the only thing you should be aware of is the character encoding, the default for text import/export is UTF8 and AFAIK package files typically are interpreted as pure ASCII. As that is a subset of UTF8 it probably only will make a difference if you use non-ascii characters within a package file (which one probably shouldn't do in the first place). I can't recall the details by heart, though, so you might need to look that up yourself... –  Albert Retey Feb 10 at 9:32
    
@AlbertRetey nice advice. So maybe it would be better to do: Export[packname,pack,"Text",CharacterEncoding->"ASCII"]? –  Murta Feb 10 at 12:32
    
@AlbertRetey, I have made a test, and it's very important, there is an simple example: Export["test1.txt","b \[Rule] a","Text"]. Without use CharacterEncoding->"ASCII", I get problem with [Rule] graphic object. Tks –  Murta Feb 10 at 12:36
    
I'm actually surprised that my comment seems more relevant than I thought. The problem is that importing and reexporting won't create the same thing as the Mathematica-specific "ascii"-encoding of special characters is only correctly done when using the CharacterEncoding option for Export. Here is an example to play with: ExportString[ImportString["b [Rule] a", "Text"], "Text"]. Of course this is mainly relevant if the package files are generated from a notebook with the auto save as package functionality, otherwise you probably won't expect such characters in a package file... –  Albert Retey Feb 10 at 15:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.