pep8speaks: Hello @mrbean-bremen! Thanks for updating the PR.

 - In the file [`pydicom/filewriter.py`](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py), following are the PEP8 issues :

> [Line 417:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L417): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (81 > 79 characters)
> [Line 421:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L421): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (88 > 79 characters)
> [Line 423:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L423): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (88 > 79 characters)




darcymason: @glemaitre, I'm assuming no further comments and going ahead to merge; please add a comment if needed.
diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py
index 4181cce16..efb596845 100644
--- a/pydicom/filewriter.py
+++ b/pydicom/filewriter.py
@@ -415,6 +415,16 @@ def write_data_element(fp, data_element, encoding=default_encoding):
     if (hasattr(data_element, "is_undefined_length")
             and data_element.is_undefined_length):
         is_undefined_length = True
+        # valid pixel data with undefined length shall contain encapsulated
+        # data, e.g. sequence items - raise ValueError otherwise (see #238)
+        if data_element.tag == 0x7fe00010:  # pixel data
+            val = data_element.value
+            if (fp.is_little_endian and not
+                    val.startswith(b'\xfe\xff\x00\xe0') or
+                    not fp.is_little_endian and
+                    not val.startswith(b'\xff\xfe\xe0\x00')):
+                raise ValueError('Pixel Data with undefined length must '
+                                 'start with an item tag')
     location = fp.tell()
     fp.seek(length_location)
     if not fp.is_implicit_VR and VR not in extra_length_VRs:

Malformed PixelData
I am trying to convert color spaces using:

``` python
        arr = convert_ybr_to_rgb(ds.pixel_array)
        ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian
        ds.is_little_endian = True
        ds.is_implicit_VR = False
        ds.PixelData = arr.tostring()
        ds.PlanarConfiguration = 0
        ds.PhotometricInterpretation = 'RGB'
```

However `dcmcjpeg` then barfs when it tries to open the saved file with:

```
W: DcmSequenceOfItems: Length of item in sequence PixelData (7fe0,0010) is odd
E: DcmSequenceOfItems: Parse error in sequence (7fe0,0010), found (292a,2a48) instead of sequence delimiter (fffe,e0dd)
F: Sequence Delimitation Item missing: reading file: /var/folders/nk/5v0p39pn4yg7c_3vtydljk000000gn/T/tmpLZfsSL.dcm
```

diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py
index 70567f134..4d7814ed0 100644
--- a/pydicom/tests/test_filewriter.py
+++ b/pydicom/tests/test_filewriter.py
@@ -41,7 +41,6 @@ except AttributeError:
     except ImportError:
         print("unittest2 is required for testing in python2.6")
 
-
 rtplan_name = get_testdata_files("rtplan.dcm")[0]
 rtdose_name = get_testdata_files("rtdose.dcm")[0]
 ct_name = get_testdata_files("CT_small.dcm")[0]
@@ -263,8 +262,8 @@ class WriteDataElementTests(unittest.TestCase):
         # Was issue 74
         data_elem = DataElement(0x00280009, "AT", [])
         expected = hex2bytes((
-            " 28 00 09 00"   # (0028,0009) Frame Increment Pointer
-            " 00 00 00 00"   # length 0
+            " 28 00 09 00"  # (0028,0009) Frame Increment Pointer
+            " 00 00 00 00"  # length 0
         ))
         write_data_element(self.f1, data_elem)
         got = self.f1.getvalue()
@@ -1731,6 +1730,74 @@ class TestWriteFileMetaInfoNonStandard(unittest.TestCase):
         self.assertEqual(meta, ref_meta)
 
 
+class TestWriteUndefinedLengthPixelData(unittest.TestCase):
+    """Test write_data_element() for pixel data with undefined length."""
+
+    def setUp(self):
+        self.fp = DicomBytesIO()
+
+    def test_little_endian_correct_data(self):
+        """Pixel data starting with an item tag is written."""
+        self.fp.is_little_endian = True
+        self.fp.is_implicit_VR = False
+        pixel_data = DataElement(0x7fe00010, 'OB',
+                                 b'\xfe\xff\x00\xe0'
+                                 b'\x00\x01\x02\x03',
+                                 is_undefined_length=True)
+        write_data_element(self.fp, pixel_data)
+
+        expected = (b'\xe0\x7f\x10\x00'  # tag
+                    b'OB\x00\x00'  # VR
+                    b'\xff\xff\xff\xff'  # length
+                    b'\xfe\xff\x00\xe0\x00\x01\x02\x03'  # contents
+                    b'\xfe\xff\xdd\xe0\x00\x00\x00\x00')  # SQ delimiter
+        self.fp.seek(0)
+        assert self.fp.read() == expected
+
+    def test_big_endian_correct_data(self):
+        """Pixel data starting with an item tag is written."""
+        self.fp.is_little_endian = False
+        self.fp.is_implicit_VR = False
+        pixel_data = DataElement(0x7fe00010, 'OB',
+                                 b'\xff\xfe\xe0\x00'
+                                 b'\x00\x01\x02\x03',
+                                 is_undefined_length=True)
+        write_data_element(self.fp, pixel_data)
+        expected = (b'\x7f\xe0\x00\x10'  # tag
+                    b'OB\x00\x00'  # VR
+                    b'\xff\xff\xff\xff'  # length
+                    b'\xff\xfe\xe0\x00\x00\x01\x02\x03'  # contents
+                    b'\xff\xfe\xe0\xdd\x00\x00\x00\x00')  # SQ delimiter
+        self.fp.seek(0)
+        assert self.fp.read() == expected
+
+    def test_little_endian_incorrect_data(self):
+        """Writing pixel data not starting with an item tag raises."""
+        self.fp.is_little_endian = True
+        self.fp.is_implicit_VR = False
+        pixel_data = DataElement(0x7fe00010, 'OB',
+                                 b'\xff\xff\x00\xe0'
+                                 b'\x00\x01\x02\x03'
+                                 b'\xfe\xff\xdd\xe0',
+                                 is_undefined_length=True)
+        with pytest.raises(ValueError, match='Pixel Data .* must '
+                                             'start with an item tag'):
+            write_data_element(self.fp, pixel_data)
+
+    def test_big_endian_incorrect_data(self):
+        """Writing pixel data not starting with an item tag raises."""
+        self.fp.is_little_endian = False
+        self.fp.is_implicit_VR = False
+        pixel_data = DataElement(0x7fe00010, 'OB',
+                                 b'\x00\x00\x00\x00'
+                                 b'\x00\x01\x02\x03'
+                                 b'\xff\xfe\xe0\xdd',
+                                 is_undefined_length=True)
+        with pytest.raises(ValueError, match='Pixel Data .+ must '
+                                             'start with an item tag'):
+            write_data_element(self.fp, pixel_data)
+
+
 if __name__ == "__main__":
     # This is called if run alone, but not if loaded through run_tests.py
     # If not run from the directory where the sample images are,

pip install -e .
parse_log_pytest
pytest
numpy>=1.16.0 pytest
apt-get update apt-get install -y gcc
3.6
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
numpy==1.19.5
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
-e git+https://github.com/pydicom/pydicom.git@1bd33e3ceec19d45844676bdd25367fda4c5319b#egg=pydicom
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work

name: pydicom
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=21.4.0=pyhd3eb1b0_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - importlib-metadata=4.8.1=py36h06a4308_0
  - importlib_metadata=4.8.1=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - more-itertools=8.12.0=pyhd3eb1b0_0
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=21.3=pyhd3eb1b0_0
  - pip=21.2.2=py36h06a4308_0
  - pluggy=0.13.1=py36h06a4308_0
  - py=1.11.0=pyhd3eb1b0_0
  - pyparsing=3.0.4=pyhd3eb1b0_0
  - pytest=6.2.4=py36h06a4308_2
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - toml=0.10.2=pyhd3eb1b0_0
  - typing_extensions=4.1.1=pyh06a4308_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - numpy==1.19.5
prefix: /opt/conda/envs/pydicom

pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data
pydicom/tests/test_filewriter.py::WriteFileTests::testCT pydicom/tests/test_filewriter.py::WriteFileTests::testJPEG2000 pydicom/tests/test_filewriter.py::WriteFileTests::testListItemWriteBack pydicom/tests/test_filewriter.py::WriteFileTests::testMR pydicom/tests/test_filewriter.py::WriteFileTests::testMultiPN pydicom/tests/test_filewriter.py::WriteFileTests::testRTDose pydicom/tests/test_filewriter.py::WriteFileTests::testRTPlan pydicom/tests/test_filewriter.py::WriteFileTests::testUnicode pydicom/tests/test_filewriter.py::WriteFileTests::test_write_double_filemeta pydicom/tests/test_filewriter.py::WriteFileTests::test_write_no_ts pydicom/tests/test_filewriter.py::WriteFileTests::testwrite_short_uid pydicom/tests/test_filewriter.py::WriteDataElementTests::test_empty_AT pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DA pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DT pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_explicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_implicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_explicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_implicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_TM pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_explicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_implicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_explicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_implicit_little pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DA pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DT pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_TM pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_big_endian pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_little_endian pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_raises pydicom/tests/test_filewriter.py::ScratchWriteTests::testImpl_LE_deflen_write pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data
pydicom/filewriter.py
pydicom/filewriter.py