将复杂文本写入文件(包括双引号和单引号)

将复杂文本写入文件(包括双引号和单引号)

我想在 python 中将一个复杂的字符串写入文件,但问题是我的文本本身有一个命令和双引号和单引号,所以 python 无法写入它并假定它也是一个命令。例如,我想将以下文本写入 file.txt:

(b'[{\n  "SourceFile": "/home/parsezan/work/hamclaasy-backend/media/3da78f6d-73a0-41d0-bca6-9b237ba13cdd/4550af6d-ac08-4d22-a80c-681bd171d295.jpg",\n  "ExifToolVersion": 10.80,\n  "FileName": "4550af6d-ac08-4d22-a80c-681bd171d295.jpg",\n  "Directory": "/home/parsezan/work/hamclaasy-backend/media/3da78f6d-73a0-41d0-bca6-9b237ba13cdd",\n  "FileSize": "112 kB",\n  "FileModifyDate": "2019:08:01 16:42:27+04:30",\n  "FileAccessDate": "2019:08:01 16:42:27+04:30",\n  "FileInodeChangeDate": "2019:08:01 16:42:27+04:30",\n  "FilePermissions": "rw-r--r--",\n  "FileType": "JPEG",\n  "FileTypeExtension": "jpg",\n  "MIMEType": "image/jpeg",\n  "JFIFVersion": 1.01,\n  "ExifByteOrder": "Big-endian (Motorola, MM)",\n  "Make": "HUAWEI",\n  "Model": "CHM-U01",\n  "Orientation": "Horizontal (normal)",\n  "XResolution": 72,\n  "YResolution": 72,\n  "ResolutionUnit": "inches",\n  "Software": "CHM-U01 V100R001C185B120",\n  "ModifyDate": "2019:07:07 11:33:18",\n  "YCbCrPositioning": "Centered",\n  "DocumentName": "",\n  "ExposureTime": "1/30",\n  "FNumber": 2.0,\n  "ExposureProgram": "Program AE",\n  "ISO": 260,\n  "ExifVersion": "0210",\n  "DateTimeOriginal": "2019:07:07 11:33:18",\n  "CreateDate": "2019:07:07 11:33:18",\n  "ComponentsConfiguration": "Y, Cb, Cr, -",\n  "ShutterSpeedValue": "1/30",\n  "ApertureValue": 2.0,\n  "BrightnessValue": 0,\n  "ExposureCompensation": 0,\n  "MeteringMode": "Average",\n  "LightSource": "Daylight",\n  "Flash": "Auto, Did not fire",\n  "FocalLength": "3.8 mm",\n  "MakerNoteUnknownText": "M[64] [e0,1] [ad,f5]",\n  "UserComment": "Hisilicon Balong",\n  "SubSecTime": 506779,\n  "SubSecTimeOriginal": 506779,\n  "SubSecTimeDigitized": 506779,\n  "FlashpixVersion": "0100",\n  "ColorSpace": "sRGB",\n  "ExifImageWidth": 4160,\n  "ExifImageHeight": 3120,\n  "InteropIndex": "R98 - DCF basic file (sRGB)",\n  "InteropVersion": "0100",\n  "SensingMethod": "One-chip color area",\n  "FileSource": "Digital Camera",\n  "SceneType": "Directly photographed",\n  "CustomRendered": "Custom",\n  "ExposureMode": "Auto",\n  "WhiteBalance": "Auto",\n  "DigitalZoomRatio": 1,\n  "FocalLengthIn35mmFormat": "27 mm",\n  "SceneCaptureType": "Standard",\n  "GainControl": "None",\n  "Contrast": "Normal",\n  "Saturation": "Normal",\n  "Sharpness": "Normal",\n  "SubjectDistanceRange": "Unknown",\n  "OffsetSchema": 60,\n  "DeviceSettingDescription": "(Binary data 4 bytes, use -b option to extract)",\n  "Compression": "JPEG (old-style)",\n  "ThumbnailOffset": 1134,\n  "ThumbnailLength": 6358,\n  "ImageWidth": 800,\n  "ImageHeight": 600,\n  "EncodingProcess": "Baseline DCT, Huffman coding",\n  "BitsPerSample": 8,\n  "ColorComponents": 3,\n  "YCbCrSubSampling": "YCbCr4:2:0 (2 2)",\n  "Aperture": 2.0,\n  "ImageSize": "800x600",\n  "Megapixels": 0.480,\n  "ScaleFactor35efl": 7.1,\n  "ShutterSpeed": "1/30",\n  "SubSecCreateDate": "2019:07:07 11:33:18.506779",\n  "SubSecDateTimeOriginal": "2019:07:07 11:33:18.506779",\n  "SubSecModifyDate": "2019:07:07 11:33:18.506779",\n  "ThumbnailImage": "(Binary data 6358 bytes, use -b option to extract)",\n  "CircleOfConfusion": "0.004 mm",\n  "FOV": "67.4 deg",\n  "FocalLength35efl": "3.8 mm (35 mm equivalent: 27.0 mm)",\n  "HyperfocalDistance": "1.70 m",\n  "LightValue": 5.5\n}]\n', None)"

我尝试:

    result = 'echo "{result}" >> file.txt'.format(result=str(raw_result))
    subprocess.Popen(result,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          shell=True)

然后尝试将其更改为dic:

    result = 'echo "{result}" >> /home/parsezan/work/django.txt'.format(result=str({'result': str(raw_result)}))
    subprocess.Popen(result,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          shell=True)

但没有人能工作。有什么想法吗?谢谢

答案1

引号需要用 \ 进行转义,以防止被 python 解释,还需要再次进行转义,以便终端不会解释它们,例如以下内容:

import subprocess
result = "echo 'this command has single quotes' and \\\"double \\\"quotes"
subprocess.Popen(
    f'echo "{result}" >> test.txt',
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=True,
)

该文件将附加以下内容:

echo'此命令有单引号'和“双”引号

然而更好的解决方案是:

with open("test.txt", "w") as out_file:
    out_file.write(result)

相关内容